zoukankan      html  css  js  c++  java
  • 39. Combination Sum(C++)

    Given a set of candidate numbers (C) (without duplicates) 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.
    • 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]
    ]

    Solution: 回溯法
    class Solution {
    public:
        
        void combination(vector<int>& candidates, int target,vector<int>& tmp,vector<vector<int>>& myvec,int start){
            if(!target){
                myvec.push_back(tmp);
                return;
            }
            for(int i=start;i<candidates.size()&&candidates[i]<=target;i++){
                tmp.push_back(candidates[i]);
                combination(candidates,target-candidates[i],tmp,myvec,i);
                tmp.pop_back();
            }
            
        }
    
        vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
            vector<vector<int>> myvec;
            sort(candidates.begin(),candidates.end());
            vector<int> tmp;
            combination(candidates,target,tmp,myvec,0);
            return myvec;
        }
    };
    

      

  • 相关阅读:
    Lucene全文检索
    数据库设计样例
    tortoisegit 保存用户名密码
    ServletContextListener 解析用法
    !! 浅谈Java学习方法和后期面试技巧
    佳能2780打印机老出5100错误
    蓝屏
    股市口诀
    如何准确进行T+0操作
    通达信:显示K线图日期
  • 原文地址:https://www.cnblogs.com/devin-guwz/p/6706058.html
Copyright © 2011-2022 走看看