【发布时间】:2012-10-19 02:45:20
【问题描述】:
我需要找到选择k 数字的方法数,这些数字加起来为n,其中1<= k <= n。数字不得重复。我正在尝试一个递归解决方案,我认为它会陷入无限循环。
void noofways(int firstnumchosen,int sum,int numofnum)
{
if(sum<0)
return;
if(sum==0 && numofnum!=0)
return;
if(sum==0 && numofnum==0){
globalcount++;
return;
}
if(numofnum<=0)
return;
// not choosing the first number
noofways(firstnumchosen+1,sum,numofnum);
//choosing the first number
noofways(firstnumchosen+1,sum-firstnumchosen,numofnum-1);
}
globalcount 在这里是一个全局变量。要使用 3 个数字得到 7 的总和,我将调用函数 noofways(1,8,3);。为了让自己更清楚,解决方案集由(1,2,5),(1,3,4)等组成。
为什么我的函数会无限运行?
【问题讨论】: