c# - 指定数量集的任意加法组合,达到特定目标值

标签 c# algorithm recursion numbers permutation

我正在寻找一种方法来获得所有可能的数字组合以达到指定的目标值。 数字集的值可以重复

例如:
号码组为4、5、6、7、8
我想要达到的值是 16。

因此,我想要这样的东西:

4+4+4+4  
4+4+8  
5+5+6  
...  

我找到的任何解决方案都没有重复,如下所示:
Efficient algorithm to find a combination, which summation is equal to a known number, in a set of number

提前致谢!

最佳答案

您也可以使用相同的递归方法。但是不要从可能的项目集中删除用过的项目。如果你想区分 a+b+aa+a+b 变体 - 遍历所有集合,如果不是 - 只遍历当前位置的项目。

function Partitions(Sum, A[], CurIdx, Result)
  if Sum = 0
     output Result
  //all variants with permutations
  for i = 0 to A.Length - 1
     if A[i] <= Sum
        Partitions(Sum - A[i], A[], i, Result + A[i])

  //variants without permutations
  for i = CurIdx to A.Length - 1
     if A[i] <= Sum
        Partitions(Sum - A[i], A[], i, Result + A[i])

  // you don't need this, just for record:  
  //variant without repeats essentially does the next:
        Partitions(Sum - A[i], A[].Remove i-th item, i, Result + A[i])

   or (note  i+1 start point for the next recursion level)

  for i = CurIdx to A.Length - 1
     if A[i] <= Sum
        Partitions(Sum - A[i], A[], i + 1, Result + A[i])

关于c# - 指定数量集的任意加法组合,达到特定目标值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49551191/

相关文章:

c# - 如何使用 Microsoft.Build.Evaluation.Project.RemoveItem

algorithm - 与 git 中的 merge 相比,rebase 有什么优势?

java - 递归打印矩阵中的所有路径

python - "Unrolling"递归函数?

c# - 使用 C# 从 Unity3D 中的输入字段获取文本

c# - 接受 float[] 和 double[] 数组的方法

c# - 使用正则表达式查找并替换特定数字

algorithm - 使用哪种多标准排序算法?

algorithm - 我的 BST findMax 有问题

C递归头文件包含问题?