lintcode 564. 组合总和 IV

给出一个都是正整数的数组 nums,其中没有重复的数。从中找出所有的和为 target 的组合个数。

样例
样例1

输入: nums = [1, 2, 4] 和 target = 4
输出: 6
解释:
可能的所有组合有:
[1, 1, 1, 1]
[1, 1, 2]
[1, 2, 1]
[2, 1, 1]
[2, 2]
[4]
样例2

输入: nums = [1, 2] 和 target = 4
输出: 5
解释:
可能的所有组合有:
[1, 1, 1, 1]
[1, 1, 2]
[1, 2, 1]
[2, 1, 1]
[2, 2]
注意事项
一个数可以在组合中出现多次。
数的顺序不同则会被认为是不同的组合。
class Solution {
public:
    /**
     * @param nums: an integer array and all positive numbers, no duplicates
     * @param target: An integer
     * @return: An integer
     */
    int backPackVI(vector<int> &nums, int target) {
        // write your code here
        vector<int> dp(target+1,0);
        dp[0]=1;
        for (int i = 0; i < target; i++) {
            for(auto num:nums)
            {
                if(i+num<=target)
                    dp[i+num]+=dp[i];
            }
        }
        return dp[target];
    }
};

你可能感兴趣的:(lintcode)