用所有可能的组合计算数字的总和

时间:2013-09-30 10:51:24

标签: java algorithm variables iteration combinations

如果存在某些数字x 0 且x n + 1 ,并且如果x i 是0 <= i的整数&lt; = n + 1,如何用JAVA计算数字的总和?

总和表示每次可能需要f(x 1 ,x 2 ,... x n )之和组合(x 1 ,x 2 ,... x n ),使不等式成立。不等式是 x 0 &lt; x 1 &lt; x 2 &lt; ......&lt; X <子> n + 1个

我对解决方案有一个想法,但它是一个使用二进制的非常无效的算法,它是O(2 n )。当然,我不能使用“for”,因为它必须用于n(非特定)时间。

例如,

如果给定x 1 = 1,并且x n + 1 是x 3 = 5,那么可能的组合是

  • x 1 = 1,x 2 = 2,x 3 = 5
  • x 1 = 1,x 2 = 3,x 3 = 5
  • x 1 = 1,x 2 = 4,x 3 = 5

总和应计算所有这3个可能值集的总和。

有没有人知道更有效的算法呢?

1 个答案:

答案 0 :(得分:2)

解决此问题的方法是将其视为尝试在nmin之间找到max个数字的所有组合。随时添加它们

您可以在nmin之间的数字线上设想max个宝石,然后将最右边的石头移动到最大值,当你移动到下一个最右边时将一块石头向上移动并向右移动所有石块。

参见此示例,其中n = 4,min = 2且max = 11

enter image description here

此算法将确保您获得所有组合。

因此,考虑到该算法,您可以编写函数

boolean[] getNextCombinations(boolean[] currentCombination) //which would advance to the next value (and probably return null when there are no more combinations)

int scoreCombinations(boolean[] currentCombination, int min, int max) //which would add up a particular combination
相关问题