带限制的整数之和

时间:2016-01-24 07:26:39

标签: recursion dynamic-programming

正确理解问题的要点:

In how many ways can we add k positive integers to reach a sum of exactly n if each number is smaller or equal to given number m?

这个问题可以通过动态编程来解决,但是因为找不到解决方案的最佳子结构或递归而陷入困境。

1 个答案:

答案 0 :(得分:1)

这是Python 3中一个适合您描述的简单函数。我假设0不是可接受的值,但是如果它是微不足道的。

def howMany(k, n, m):

    def sub(pos, currentSum, path):
        if currentSum == n and pos == k: # reached the sum, print result and increase counter by 1
            print(path)
            return 1
        elif currentSum < n and pos < k: # still worth trying
            count = 0
            for i in range(1, m):
                count += sub(pos + 1, currentSum + i, path+[i])
            return count
        else: # abort
            return 0

    return sub(0, 0, [])

print(howMany(3, 10, 6))

产量

[1, 4, 5]
[1, 5, 4]
[2, 3, 5]
[2, 4, 4]
[2, 5, 3]
[3, 2, 5]
[3, 3, 4]
[3, 4, 3]
[3, 5, 2]
[4, 1, 5]
[4, 2, 4]
[4, 3, 3]
[4, 4, 2]
[4, 5, 1]
[5, 1, 4]
[5, 2, 3]
[5, 3, 2]
[5, 4, 1]
18

可以对其进行优化,但这会在现阶段模糊逻辑。