题目:
Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
思路:
动态规划公式为dp[i]+=dp[i-x], x属于nums中的每个元素
,dp[i]表示和为i的所有组合总数。
代码实现:
class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
if (nums.empty()){
return 0;
}
vector<unsigned int> dp(target+1);
dp[0] = 1; // 当出现dp[x-x]==dp[0]时,说明这是一种只包含x自己的组合
for (int i = 1; i <= target; ++i){
for (int j = 0; j < nums.size(); ++j){
if (i >= nums[j]){
dp[i] += dp[i-nums[j]];
}
}
}
return (int)dp.back();
}
};