zoukankan      html  css  js  c++  java
  • LeetCode_Combination Sum

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

      

    class Solution {
    public:
        void  DFS(vector<int> &candidates, int target, int start, int sum, vector<int> &tp){
    		if(sum == target){
    			res.push_back(tp);
    			return;
    		}
    		for(int i = start; i< candidates.size(); ++i){
    			if(candidates[i] + sum <= target){
    				tp.push_back(candidates[i]);
    				DFS(candidates, target, i, sum+candidates[i], tp);
    				tp.pop_back();
    			}
    		}
    	}
        vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            res.clear();
    		int len = candidates.size();
    		if(len < 1 || target <1) return res;
    		sort(candidates.begin(), candidates.end());
    		vector<int> tp;
    		DFS(candidates, target, 0, 0, tp);
    		return res;
    		
        }
    private:
    	vector<vector<int>> res;
    };
    

      

  • 相关阅读:
    手机号码正则表达式
    POJ 3233 Matrix Power Series 矩阵快速幂
    UVA 11468
    UVA 1449
    HDU 2896 病毒侵袭 AC自动机
    HDU 3065 病毒侵袭持续中 AC自动机
    HDU 2222 Keywords Search AC自动机
    POJ 3461 Oulipo KMP模板题
    POJ 1226 Substrings KMP
    UVA 1455 Kingdom 线段树+并查集
  • 原文地址:https://www.cnblogs.com/graph/p/3322746.html
Copyright © 2011-2022 走看看