您的位置:首页 > 其它

OJ 求硬币组合数

2015-06-07 12:00 274 查看
public static int calculateChanges(String coinTypes)
{
final int totleMoney = 1000;
int totlceChangesNum = 0;

//1 正确性校验
//1.1 必须有且只有2个逗号
int sep1 = -1;
int sep2 = -1;
int sep3 = -1;
sep1 = coinTypes.indexOf(',');
//必须有1个逗号并且第一个的位置不是在0
if(sep1 == -1 ||sep1 == 0)
{
return -1;
}
else
{
//必须有第2个逗号 并且第2个的位置不能在末尾
sep2 = coinTypes.indexOf(',' , sep1 + 1);
//System.out.println("sep2 is  " + sep2);
if(sep2 == -1 || sep2 == sep1 + 1 || sep2 == coinTypes.length() -1)
{
return -1;
}
else
{
sep3 = coinTypes.indexOf(',' , sep2 + 1);
//如果有3个以上的逗号
if(sep3 != -1)
{
return -1;
}
}
}

//1.2 校验只有2个逗号通过后校验数字正确性
String [] inputString =  coinTypes.split(",");
int [] inputInt = new int[3];
for(int i =0; i < inputString.length; i++)
{
inputInt[i] = Integer.parseInt(inputString[i]);
//校验数字正确性
if(inputInt[i] != 1 && inputInt[i] != 2 && inputInt[i] !=  5 && inputInt[i] !=  10 && inputInt[i] !=  50 && inputInt[i] != 100 )
{
return -1;
}
}

//按升序排列
Arrays.sort(inputInt);
//1.3 校验数字重复性
if(inputInt[0] == inputInt[1] ||inputInt[1] == inputInt[2] )
{
return -1;
}

//2 计算排列个数
//2.1 保存计算每个数字的最大可能数量
int [] inputMaxNum = new int [3];
for(int i = 0; i < 3 ; i++)
{
inputMaxNum[i] = totleMoney / inputInt[i];
}

//2.2 计算总体组合数量
for(int i = 1; i < inputMaxNum[0]; i ++)
{
//除去最大的数后的剩余最大次数
for(int j = 1; j < inputMaxNum[1];j ++)
{
//除去两次后的最大次数
for(int k = 1; k < inputMaxNum[2] ; k ++)
{
if(inputInt[0] * i + inputInt[1] * j + inputInt[2] * k == 1000)
{

totlceChangesNum++;
}
}
}
}
return totlceChangesNum;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: