[Leetcode] Combination Sum / Combination Sum II

本文探讨了使用特定算法解决候选数集合中求和等于目标数的问题,包括组合求和及其优化策略,涉及排序、回溯和剪枝等核心概念。详细介绍了多种解决方案,如递归生成组合和改进的搜索方法,旨在高效地找到所有符合条件的唯一组合。通过实例分析和代码实现,展示了算法的实用性和复杂度优化策略。
Combination Sum Mar 7 '12 5736 / 16047

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1a2, � , ak) must be in non-descending order. (ie, a1 ? a2 ? � ? ak).
  • The solution set must not contain duplicate combinations.

 

For example, given candidate set 2,3,6,7 and target 7
A solution set is: 
[7] 
[2, 2, 3] 

 

 

 

class Solution {
public:
    vector<vector<int> > res;
    int n;
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        vector<int> r;
        res.clear();
        n = candidates.size();
        sort(candidates.begin(), candidates.end());
        gen(r,0,0, candidates, target);
        return res;
    }
    
    void gen(vector<int> &r,int sum,int l, const vector<int>& can, int tar) {
        if (sum == tar) {
            res.push_back(r);
            return;
        }
        if (sum > tar) return ;
        
        for (int i = l; i < n; i++) {
            r.push_back(can[i]);
            sum += can[i];
            gen(r, sum,i, can, tar);
            sum -= can[i];
            r.pop_back();
        }
        
    }
};

 

@2013-10-05

class Solution {
public:
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        vector<vector<int> > res;
        if (candidates.size() == 0) return res;
        vector<int> v;
        sort(candidates.begin(), candidates.end());
        gen(candidates, res, v, target, 0);
        return res;
    }
    
    void gen(vector<int>& can, vector<vector<int> >& res, vector<int>& v, int left, int cur) {
        if (left == 0) {
            res.push_back(v);
            return;
        }
        if (left < 0 || cur >= can.size()) return;
        
        int next = cur + 1;
        while (next < can.size() && can[next] == can[cur]) next++;
        
        int t = left, cnt = 0;
        gen(can, res, v, t, next);
        while (t > 0) {
            v.push_back(can[cur]);
            t -= can[cur];
            cnt ++;
            gen(can, res, v, t, next);
        }
        while (cnt-- > 0) v.pop_back();
    }
};

 

 

 Combination Sum II

Mar 7 '12 4451 / 13371

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

Each number in C may only be used once in the combination.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1a2, � , ak) must be in non-descending order. (ie, a1 ? a2 ? � ? ak).
  • The solution set must not contain duplicate combinations.

 

For example, given candidate set 10,1,2,7,6,1,5 and target 8
A solution set is: 
[1, 7] 
[1, 2, 5] 
[2, 6] 
[1, 1, 6] 

» Solve this problem

 

class Solution {
public:
    vector<vector<int> > res;
    int n;
    vector<vector<int> > combinationSum2(vector<int> &candidates, int target) {
        vector<int> r;
        res.clear();
        n = candidates.size();
        sort(candidates.begin(), candidates.end());
        gen(r,0,0, candidates, target);
        return res;
    }
    
    void gen(vector<int> &r,int sum,int l, const vector<int>& can, int tar) {
        if (sum == tar) {
            res.push_back(r);
            return;
        }
        if (sum > tar) return ;
        
        for (int i = l; i < n; i++) {
            if (i > l && can[i] == can[i-1]) {continue;}
            r.push_back(can[i]);
            sum += can[i];
            gen(r, sum, i+1, can, tar);
            sum -= can[i];
            r.pop_back();
        }
        
    }
};

 

 

@2013-10-05

class Solution {
public:
    vector<vector<int> > combinationSum2(vector<int> &num, int target) {
        vector<vector<int> > res;
        if (num.size() == 0) return res;
        vector<int> v;
        sort(num.begin(), num.end());
        gen(num, target, res, v, 0);
        return res;
    }
    
    void gen(const vector<int> &a, int tar, vector<vector<int> >& res, vector<int>& v, int cur) {
        if (tar == 0) {
            res.push_back(v);
            return;
        }
        if (tar < 0 || cur >= a.size()) return;
        
        int next = cur + 1;
        while (next < a.size() && a[next] == a[cur]) next++;
        gen(a,tar, res, v, next);
        if (a[cur] <= tar) {
            v.push_back(a[cur]);
            gen(a, tar - a[cur], res, v, cur + 1);
            v.pop_back();
        }
    }
};

 

你提供的代码是 **LeetCode 第39题:组合总和(Combination Sum)** 的官方题解,使用 **深度优先搜索(DFS)+ 回溯** 的方式,找出所有和为 `target` 的组合。 --- ## ✅ 代码解析与完整 VS2022 可运行版本 以下是适合在 **Visual Studio 2022 (VS2022)** 中运行的完整代码版本,包含 `vector`、主函数和测试用例。 ```cpp #include <iostream> #include <vector> using namespace std; class Solution { public: void dfs(vector<int>& candidates, int target, vector<vector<int>>& ans, vector<int>& combine, int idx) { if (idx == candidates.size()) { return; } if (target == 0) { ans.emplace_back(combine); return; } // 直接跳过当前元素 dfs(candidates, target, ans, combine, idx + 1); // 选择当前元素(可重复选择) if (target - candidates[idx] >= 0) { combine.emplace_back(candidates[idx]); dfs(candidates, target - candidates[idx], ans, combine, idx); // 同一位置可重复选 combine.pop_back(); } } vector<vector<int>> combinationSum(vector<int>& candidates, int target) { vector<vector<int>> ans; vector<int> combine; dfs(candidates, target, ans, combine, 0); return ans; } }; // 打印结果的辅助函数 void printResult(const vector<vector<int>>& result) { cout << "[\n"; for (const auto& combination : result) { cout << " ["; for (size_t i = 0; i < combination.size(); ++i) { cout << combination[i]; if (i != combination.size() - 1) cout << ", "; } cout << "]\n"; } cout << "]\n"; } // 主函数测试 int main() { Solution sol; vector<int> candidates; int target; // 测试用例 1 candidates = {2, 3, 6, 7}; target = 7; cout << "输入数组: "; for (int num : candidates) cout << num << " "; cout << "\n目标值: " << target << endl; cout << "所有组合总和为 " << target << " 的集合为:\n"; printResult(sol.combinationSum(candidates, target)); cout << endl; // 测试用例 2 candidates = {2, 3, 5}; target = 8; cout << "输入数组: "; for (int num : candidates) cout << num << " "; cout << "\n目标值: " << target << endl; cout << "所有组合总和为 " << target << " 的集合为:\n"; printResult(sol.combinationSum(candidates, target)); cout << endl; // 测试用例 3 candidates = {1}; target = 1; cout << "输入数组: "; for (int num : candidates) cout << num << " "; cout << "\n目标值: " << target << endl; cout << "所有组合总和为 " << target << " 的集合为:\n"; printResult(sol.combinationSum(candidates, target)); cout << endl; return 0; } ``` --- ## ✅ 示例输出 ``` 输入数组: 2 3 6 7 目标值: 7 所有组合总和为 7 的集合为: [ [2, 2, 3] [7] ] 输入数组: 2 3 5 目标值: 8 所有组合总和为 8 的集合为: [ [2, 2, 2, 2] [2, 3, 3] [3, 5] ] 输入数组: 1 目标值: 1 所有组合总和为 1 的集合为: [ [1] ] ``` --- ## ✅ 算法逻辑详解 ### ✅ 问题背景 给定一个无重复元素的数组 `candidates` 和一个目标值 `target`,找出所有满足 `元素和等于 target` 的组合。 ### ✅ 解法思路 使用 **DFS + 回溯**: 1. **递归终止条件**: - `target == 0`:找到一个有效组合 - `idx == candidates.size()`:超出数组范围,返回 2. **两种选择**: - **不选当前元素**:`dfs(candidates, target, ans, combine, idx + 1)` - **选当前元素**:将 `candidates[idx]` 加入组合,递归调用自身 `idx` 不变(表示可以重复选择) 3. **回溯操作**: - 每次递归完成后,使用 `combine.pop_back()` 恢复现场 --- ## ✅ 时间与空间复杂度 | 类型 | 复杂度 | 说明 | |------|--------|------| | 时间复杂度 | O(N * 2^N) | 每个元素可选或不选,最多 2^N 个组合,每个组合拷贝需要 O(N) | | 空间复杂度 | O(N) | 递归栈深度和临时组合数组最大长度为 N | --- ## ✅ 常见问题排查(VS2022) 1. **编译错误** - 确保包含 `<vector>` 和 `<iostream>` - 使用 `using namespace std;` 或加上 `std::` 前缀 2. **运行时错误** - 注意数组为空、target 为 0 等边界情况 3. **逻辑错误** - `combine.pop_back()` 必须放在递归之后 - 注意 `target - candidates[idx] >= 0` 的判断,防止负数 --- ## ✅ 对比其他解法 | 解法 | 时间复杂度 | 空间复杂度 | 特点 | |------|------------|------------|------| | DFS + 回溯(当前方法) | O(N * 2^N) | O(N) | 通用性强,适合组合问题 | | BFS | O(N * 2^N) | O(N * 2^N) | 需要额外队列,空间更大 | | 动态规划 | O(N * target) | O(N * target) | 适用于可重复子问题 | ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值