Is there an efficient algorithm for integer partitioning with restricted number of parts?

前端 未结 5 892
天涯浪人
天涯浪人 2020-12-01 11:32

I have to create a method that takes two integers, let them be n and m, and returns how many ways there are to sum m positive numbers

5条回答
  •  感情败类
    2020-12-01 12:07

    You could use dynamic programming. Let f[n][m][k] be the number of of partitions of m non-decreasing positive numbers such that the sum is n and the last one is k. Then you could easily see that the update step would be:

    f[n][m][k] → f[n+l][m+1][l] for every l≥ k
    

    To get f[n][m], meaning the number of all partitions independent on which is the last number, at the end just sum over all k. The complexity would be O(n^2 m).

提交回复
热议问题