【问题标题】:Finding number of ways to select k numbers that add upto n找到选择 k 个数的方法数,这些数加起来为 n
【发布时间】: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)等组成。

为什么我的函数会无限运行?

【问题讨论】:

    标签: c algorithm recursion


    【解决方案1】:

    noofways(x, y, z) 调用 noofways(x+1, y, z),因此 x 无限增长。

    需要在参数检查时测试x是否过大并返回:

    if (firstnumchosen > something)
        return;
    

    这不是唯一的问题,但它是无限循环的原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-31
      • 1970-01-01
      • 2017-07-02
      • 1970-01-01
      • 1970-01-01
      • 2015-10-19
      • 1970-01-01
      • 2016-04-02
      相关资源
      最近更新 更多