LeetCode刷题实战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)
请注意,顺序不同的序列被视作不同的组合。
示例 2:
输入:nums = [9], target = 3
输出:0
解题
class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
// dp[i]:target为i时的组合数目
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];
}
};
评论