• [LeetCode] Combination Sum


    Note:

    • All numbers (including target) will be positive integers.
    • Elements in a combination (a1, a2, … , 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] 

    思路,对于2,从2开始,对于3,从3开始,保证不会出现322,只会出现223, 其实还是回溯法,或者说dfs,如下图所示

    code1:在红字出剪纸,

    class Solution
    {
        vector<vector<int> > m_result;
        public:
    
        void dfs(const vector<int> &candidates, int target, vector<int>& array, int start) 
        {   
            if(target < 0)
                return;
            if(target == 0)
            {   
                m_result.push_back(array);
                return;
            }   
    
            for(size_t i = start; i < candidates.size(); i++)
            {   
                array.push_back(candidates[i]);
                dfs(candidates, target - candidates[i], array, i); 
                array.pop_back();
            }   
        }   
    
        vector<vector<int> > combinationSum(vector<int> &candidates, int target)
        {   
            vector<int> array;
            sort(candidates.begin(), candidates.end());
            vector<int>::iterator pos = unique(candidates.begin(), candidates.end());  
            candidates.erase(pos, candidates.end()); 
            dfs( candidates, target, array, 0); 
    
            return m_result;
        }   
    };

    code2:在红字出剪纸。

    class Solution
    {
        vector<vector<int> > m_result;
        public:
    
        void dfs(const vector<int> &candidates, int target, vector<int>& array, int start) 
        {   
            if(target == 0)
            {   
                m_result.push_back(array);
                return;
            }   
    
            for(size_t i = start; i < candidates.size(); i++)
            {   
                if(target < candidates[i])
                    return;
                array.push_back(candidates[i]);
                dfs(candidates, target - candidates[i], array, i); 
                array.pop_back();
            }   
        }   
    
        vector<vector<int> > combinationSum(vector<int> &candidates, int target)
        {   
            vector<int> array;
            sort(candidates.begin(), candidates.end());
            vector<int>::iterator pos = unique(candidates.begin(), candidates.end());  
            candidates.erase(pos, candidates.end()); 
            dfs( candidates, target, array, 0); 
    
            return m_result;
        }   
    };
  • 相关阅读:
    JavaScript向input标签的value赋值
    thinkphp关于本地引用图片
    jquery中得到input的值
    HTML的video标签,不能下载视频代码
    PHP数据库类
    MySQL数据库之MyISAM与InnoDB的区别
    php函数ob_start(),解决header输出头报错问题
    eps图片中文乱码问题
    感悟----程序员需要养成的习惯
    <前m大的数>的妙解
  • 原文地址:https://www.cnblogs.com/diegodu/p/4284579.html
Copyright © 2020-2023  润新知