C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了给定一个数组,找到小于c的n个数字的组合大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
这是一个艰难的,至少我的最低技能.

基本上,用户将价格列表输入到阵列中,然后输入他想要购买的所需数量的项目,最后是不超过的最大成本.

我需要检查所需数量的项目的组合数量是否小于或等于给定的成本.

如果问题是组合中固定数量的项目,比如说3,只需要三个循环选择每个价格并添加它们进行测试就会容易得多.

我感到难过的地方是要求用户输入任意数量的项目,直到数组中的项目数量.

这是我最初决定的,然后才意识到用户可以指定任意数字的组合,而不仅仅是三个.它是在这里的类似主题的帮助下创建的,但同样只有当用户指定他想要每个组合3个项目时它才有效.否则它不起作用.

// test if any combinations of items can be made
  for (one = 0; one < (count-2); one++) // count -2 to account for the two other variables
  {
    for (two = one + 1; two < (count-1); two++) // count -1 to account for the last variable
    {
      for (three = two + 1; three < count; three++)
      {
        @R_412_10586@l = itemCosts[one] + itemCosts[two] + itemCosts[three];
        if (@R_412_10586@l <= funds)
        {
          // DEBUG printf("\nMatch found! %d + %d + %d,@R_412_10586@l: %d.",itemCosts[one],itemCosts[two],itemCosts[three],@R_412_10586@l);
          combos++;
        }
      }
    }
  }

据我所知,根据用户所需的每个组合的项目数量,没有简单的方法可以使其灵活适应.

我真的很感激任何帮助.

@R_@R_502_2481@_1964@

扁平嵌套迭代的一个技巧是使用递归.

创建一个函数,该函数包含您到目前为止所选择的项目数,以及您在此时选择的项目数.算法应该是这样的

>如果您已选择等于目标N的项目数,请计算总和并根据限制进行检查
>如果您没有选择足够的项目,请在列表中再添加一项,然后进行递归调用.

为确保您不会选择相同的项目两次,请传递函数可以选择的最小索引.函数的声明可能如下所示:

int count_combinations(
    int itemCosts[],size_t costCount,int pickedItems[],size_t pickedCount,size_t pickedTargetCount,size_t minIndex,int funds
) {
    if (pickedCount == pickedTargetCount) {
        // This is the base case. It has the code SIMILAR TO
        // the "if" statement from your code,but the number of items
        // is not fixed.
        int sum = 0;
        for (size_t i = 0 ; i != pickedCount ; i++) {
            sum += pickedItems[i];
        }
        // The following line will return 0 or 1,// depending on the result of the comparison.
        return sum <= funds;
    } else {
        // This is the recursive case. it is SIMILAR TO one of your "for"
        // loops,but instead of setTing "one","two",or "three"
        // it sets pickedItems[0],pickedItems[1],etc.
        int res = 0;
        for (size_t i = minIndex ; i != costCount ; i++) {
            pickedItems[pickedCount] = itemCosts[i];
            res += count_combinations(
                itemCosts,costCount,pickedItems,pickedCount+1,pickedTargetCount,i+1,funds
            );
        }
        return res;
    }
}

你可以这样调用这个函数

int itemCosts[C] = {...}; // The costs
int pickedItems[n]; // No need to initialize this array
int res = count_combinations(itemCosts,C,N,funds);

Demo.

大佬总结

以上是大佬教程为你收集整理的给定一个数组,找到小于c的n个数字的组合全部内容,希望文章能够帮你解决给定一个数组,找到小于c的n个数字的组合所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。