zoukankan      html  css  js  c++  java
  • 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
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    SVN:cannot map the project with svn provider解决办法
    项目管理工具_maven的配置
    servlet,过滤器,监听器,拦截器的区别
    索引
    事务的隔离级别和传播行为
    jbpm工作流
    Hibernate---进度1
    java——反射
    HttpClient
    TCP和UDP并实现socket的简单通信
  • 原文地址:https://www.cnblogs.com/dysjtu1995/p/12292016.html
Copyright © 2011-2022 走看看