• 40. Combination Sum II


    Problem:

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

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

    Note:

    • All numbers (including target) will be positive integers.
    • The solution set must not contain duplicate combinations.

    Example 1:

    Input: candidates = [10,1,2,7,6,1,5], target = 8,
    A solution set is:
    [
      [1, 7],
      [1, 2, 5],
      [2, 6],
      [1, 1, 6]
    ]
    

    Example 2:

    Input: candidates = [2,5,2,1,2], target = 5,
    A solution set is:
    [
      [1,2,2],
      [5]
    ]
    

    思路

    和39题类似的思路,利用递归求解。注意要除去重复的结果。

    Solution (C++):

    public:
        vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
            sort(candidates.begin(), candidates.end());
            vector<vector<int>> res;
            vector<int> combination;
            combinationSum2(candidates, target, res, combination, 0);
            
            return res;
        }
    private:
        void combinationSum2(vector<int> &candidates, int target, vector<vector<int>> &res, vector<int> &combination, int begin) {
            if (target == 0) {
                res.push_back(combination);
                return;
            }
            else {
                for (int i = begin; i < candidates.size() && target >= candidates[i]; ++i) {
                    if (i && candidates[i] == candidates[i-1] && i > begin)  continue;        //检查是否重复
                    combination.push_back(candidates[i]);
                    combinationSum2(candidates, target-candidates[i], res, combination, i+1);
                    combination.pop_back();
                }
            }
        }
    

    性能

    Runtime: 8 ms  Memory Usage: 8.9 MB

    相关链接如下:

    知乎:littledy

    欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

    作者:littledy
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    C#的显式接口和隐式接口
    Working with XML in a Classic COM Application
    规格单位换算
    C#压缩解压缩(文件夹里包含文件夹)
    在线编辑器原理
    右键新建文本文档没有了。
    MemoryStream读写
    gacutil.exe ,RegAsm.exe 和全局缓存(GAC)
    OData services入门使用ASP.NET Web API描述
    Readonly和Disabled
  • 原文地址:https://www.cnblogs.com/dysjtu1995/p/12292016.html
Copyright © 2020-2023  润新知