?LeetCode刷題實(shí)戰(zhàn)377:組合總和 Ⅳ
Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to target.
The answer is guaranteed to fit in a 32-bit integer.
示例
示例 1:
輸入:nums = [1,2,3], target = 4
輸出:7
解釋:
所有可能的組合為:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
請(qǐng)注意,順序不同的序列被視作不同的組合。
示例 2:
輸入:nums = [9], target = 3
輸出:0
解題
class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
// dp[i]:target為i時(shí)的組合數(shù)目
vector<int> dp(target+1, 0);
dp[0] = 1;
for(int i = 1; i < target + 1;++i){
for(auto num:nums){
if(num <= i && dp[i-num] < INT_MAX - dp[i]) // 防止越界
dp[i] += dp[i - num];
}
}
return dp[target];
}
};
LeetCode1-360題匯總,希望對(duì)你有點(diǎn)幫助!
LeetCode刷題實(shí)戰(zhàn)361:轟炸敵人
LeetCode刷題實(shí)戰(zhàn)362:敲擊計(jì)數(shù)器
評(píng)論
圖片
表情
