【问题标题】:Algorithm to find the number of ways a number can be written as a sum of two or more positive numbers找出一个数字可以写成两个或多个正数之和的方法数的算法
【发布时间】:2015-04-29 00:06:28
【问题描述】:

这是一道作业题,必须使用动态编程方法来解决。

到目前为止,我所做的是:

让 f(x) 表示 x 可以写的次数:

那么 f(x) = f(x - 1) + 1 ; f(5) = f(4) + 1 (5 = 4 + 1)

但我认为这不是正确的方法。有人愿意帮忙吗?

一个真正的问题的例子:

4的写法数:

4: 3 + 1
4: (2 + 1) + 1
4: 2 + 2
4: (1 + 1) + (1 + 1)

【问题讨论】:

    标签: recursion dynamic-programming memoization integer-partition


    【解决方案1】:

    这个表示是调用partition。它可以通过不同的方式解决。

    例如,假设

    f(x, m) - number of partitions of x 
    such that the largest number in that partition is m
    

    然后

    f(x, m) = sum of all f(x - m, k) where (1 <= k <= m),
    also (k<=x-m), because f(x, y) = 0 where (y > x)
    

    对于您的示例(让我们将数字本身也算作一个分区(f(x,x)= 1))

    f(1, 1) = 1
    f(2, 1) = f(1, 1) = 1
    f(2, 2) = 1
    f(3, 1) = f(2, 1) = 1
    f(3, 2) = f(1, 1) = 1 //+ f(1, 2) zero
    f(4, 1) = f(3, 1) = 1 
    f(4, 2) = f(2, 1) + f(2, 2) = 2
    f(4, 3) = f(1, 1) = 1 // + f(1, 2) + f(1, 3) zeroes
    f(4, 4) = 1
    

    所以 f(4, 1), f(4, 2), f(4, 3), f(4, 4) = 5 ( 4 如果不计算 4 本身就是一个分区)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-14
      • 2017-06-13
      • 1970-01-01
      • 2013-10-08
      • 2013-11-15
      相关资源
      最近更新 更多