LeetCode --- Combination Sum

来源:互联网 发布:php前台模板 编辑:程序博客网 时间:2024/05/01 07:48

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]

My Submitted Code

class Solution {    vector<vector<int> > result;    vector<int> vcand;    vector<int> tmp;    int tmp_sum(vector<int>& v){        int ret=0;        int size=v.size();        for(int i=0;i<size;i++){            ret+=v[i];        }        return ret;    }    void dfs(int target,int l){        if(l == vcand.size()){            return;        }        int tsum=tmp_sum(tmp);        if(tsum == target){            result.push_back(tmp);            return ;        }        else if(tsum > target){            return;        }else{            int size=vcand.size();            for(int i=l;i<size;i++){                tmp.push_back(vcand[i]);                dfs(target,i);                tmp.pop_back();            }        }    }public:    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {        sort(candidates.begin(),candidates.end());        tmp.clear();        vcand=candidates;        dfs(target,0);        return result;    }};
0 0
原创粉丝点击