第十週 動態規劃 Combination Sum IV
阿新 • • 發佈:2019-01-30
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:
nums = [1, 2, 3]
target = 4
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
Therefore the output is 7.
**
思路
**
題目給定一個正整數陣列和一個目標值,希望找到能由陣列中的元素可重複地相加得到目標值的方案個數。
使用動態規劃的思想,設s【i】表示能由陣列中元素可重複相加得到i的方案個數,nums【j】表示陣列中第j個元素。當i=0,1…n - 1的s【i】都求得時,則s【n】=∑ s【n - nums[j]】(nums[j] <= n)。
**原始碼**
--
class Solution {
public:
int combinationSum4(vector <int>& nums, int target) {
if(nums.size() == 0)
return 0;
int s[100000],i,j,count;
s[0] = 1;
for(i = 1;i <= target;i ++){
count = 0;
for(j = 0;j < nums.size();j ++){
if(nums[j] <= i){
count += s[i - nums[j]];
}
}
s[i] = count;
}
return s[target];
}
};