zoukankan      html  css  js  c++  java
  • 39. 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>& a,vector<vector<int>>&v,vector<int>&tmp,int id,int sum,int target){
            if(sum>target)return ;
            if(sum==target){
                v.push_back(tmp);
                return ;
            }
            for(int i=id;i<a.size();i++){
                if(a[i]+sum>target)break;//重要的剪枝
                tmp.push_back(a[i]);
                dfs(a,v,tmp,i,sum+a[i],target);
                tmp.pop_back();
            }
        }
        vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
            sort(candidates.begin(),candidates.end());
            vector<vector<int>>v;
            vector<int>tmp;
            dfs(candidates,v,tmp,0,0,target);
            return v;
        }
    };
  • 相关阅读:
    RTP/RTSP编程
    makefile
    VS 2010内存泄漏检测
    Linux Shell中捕获CTRL+C
    const
    Hdu 5344
    Hdu5762
    CF1200C
    CF1200B
    CF1200A
  • 原文地址:https://www.cnblogs.com/pk28/p/5355728.html
Copyright © 2011-2022 走看看