Description
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.
Example:
Thinking
用动态规划解决这个问题。用nums中的数字加出target,求共有多少种组合方式。设置一个size为target+1的vector tar用于记录加法总数,假设target为0,则只有一种,不用任何nums中的数字,即tar[0]=1。
求tar[i]时,遍历nums数组,若tar[i]大于nums[j],则增加tar[i-nums[j]]种方法。状态转移方程如下:
tar[i] += tar[i - nums[j]];
Solution
class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
vector<int> tar(target + 1, 0);
tar[0] = 1;
for(int i = 1; i <= target; i++){
for(int j = 0; j < nums.size(); j++){
int num = nums[j];
if(i - nums[j] >= 0){
tar[i] += tar[i - num];
}
}
}
return tar[target];
}
};