[LintCode] k Sum

Given n distinct positive integers, integer k (k <= n) and a number target.

Find k numbers where sum is target. Calculate how many solutions there are?

Example

Given [1,2,3,4], k=2, target=5. There are 2 solutions:

[1,4] and [2,3], return 2.

http://www.lintcode.com/en/problem/k-sum/

dp[k][v] 表示使用了k个数和为v的方案数,那么对于新加入的一个数a,状态转移方程为:

dp[k][v] += dp[k-1][v-a];

下面是AC代码。

 1 class Solution {

 2 public:

 3     /**

 4      * @param A: an integer array.

 5      * @param k: a positive integer (k <= length(A))

 6      * @param target: a integer

 7      * @return an integer

 8      */

 9     

10     int kSum(vector<int> A, int k, int target) {

11         // wirte your code here

12         vector<vector<int> > dp(k + 1, vector<int>(target + 1, 0));

13         dp[0][0] = 1;

14         for (auto a : A) {

15             for (int kk = k; kk > 0; --kk) {

16                 for (int v = target; v >= a; --v) {

17                     dp[kk][v] += dp[kk-1][v - a];

18                 }

19             }

20         }

21         return dp[k][target];

22     }

23 };

 

你可能感兴趣的:(code)