给定一个由正整数组成且不存在重复数字的数组,找出和为给定目标正整数的组合的个数。
示例:
nums = [1, 2, 3]
target = 4
所有可能的组合为:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
请注意,顺序不同的序列被视作不同的组合。
因此输出为 7。
来源:力扣(LeetCode)
链接:传送门
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
超时dfs:
class Solution {
public:
void dfs(vector<int>& nums, int target, int& count){
if(target < 0) return;
for(auto num : nums){
if(num < target){
dfs(nums, target - num, count);
}else if(num == target) {
count++;
}else break;
}
return;
}
int combinationSum4(vector<int>& nums, int target) {
if(nums.size() == 0 || target == 0) return 0;
sort(nums.begin(), nums.end());
int count = 0;
dfs(nums, target, count);
return count;
}
};
背包问题,动态规划 dp[i] += dp[i-num] :
class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
vector<unsigned long long> dp(target+1, 0);
dp[0] = 1;
sort(nums.begin(), nums.end());
for(int i = 1; i <= target; ++i){
for(auto num : nums){
if(i >= num) {
dp[i] += dp[i-num];
}else break;
}
}
return dp[target];
}
};
本文深入探讨了组合求和IV问题,通过示例详细解释了如何找出由正整数组成的数组中,和为目标正整数的所有组合的个数。提供了两种解决方案,一种是超时的深度优先搜索(DFS),另一种是高效的动态规划(DP)方法。
615

被折叠的 条评论
为什么被折叠?



