題目:
給定數組,找到所有加起來等於給定值得所有組合個數
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.
算法:
使用遞歸會超時,使用dp
i從1到target計算可能的組合數,如果i>nums數組裏的x,那麼dp[i] += dp[i-x].
比如說對於[1,2,3] 4,這個例子,當我們在計算dp[3]的時候,3可以拆分爲1+x,而x即爲dp[2],3也可以拆分爲2+x,此時x爲dp[1],3同樣可以拆爲3+x,此時x爲dp[0],我們把所有的情況加起來就是組成3的所有情況了。
class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
if(nums.empty())
return 0;
vector<int>dp(target+1);
dp[0] = 1;
for (int i = 1; i <= target; ++i) {
for (auto x : nums){
if(i >= x){
dp[i] += dp[i-x];
}
}
}
return dp.back();
}
};