• 39. Combination Sum


    Problem:

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

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

    Note:

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

    Example 1:

    Input: candidates = [2,3,6,7], target = 7,
    A solution set is:
    [
      [7],
      [2,2,3]
    ]
    

    Example 2:

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

    思路

    采用回溯法(BackTracking)。

    Solution (C++):

    public:
        vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
            sort(candidates.begin(), candidates.end());
            vector<vector<int>> res;
            vector<int> combination;
            combinationSum(candidates, target, res, combination, 0);
            
            return res;
        }
    private:
        void combinationSum(vector<int> &candidates, int target, vector<vector<int>> &res, vector<int> &combination, int begin) {
            if (target == 0) {
                res.push_back(combination);
                return ;
            }
            for (int i = begin; i < candidates.size() && target >= candidates[i]; ++i) {
                combination.push_back(candidates[i]);
                combinationSum(candidates, target - candidates[i], res, combination, i);    //不是解则无变化,pop掉尾部的数
                combination.pop_back(candidates[i]);
            }
        }
    

    性能

    Runtime: 12 ms  Memory Usage: 9.5 MB

    相关链接如下:

    知乎:littledy

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

    作者:littledy
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    JVM内存结构解析
    tomcat服务器日志分页
    20多个常用的免费WebService接口
    将tomcat设置在服务中为开机自动启动
    oracle11g安装常见错误
    Resultset 转化成list或map
    SprngMVC工作原理
    Spring中ContextLoaderListener作用
    oracle如何导出和导入数据库/表
    轻松搭建Redis缓存高可用集群
  • 原文地址:https://www.cnblogs.com/dysjtu1995/p/12286664.html
Copyright © 2020-2023  润新知