[leetcode 39] Combination Sum

来源:互联网 发布:ajax返回json为null 编辑:程序博客网 时间:2024/06/09 17:20

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 (a1a2, … , 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:    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {        vector<int> cur;        vector<vector<int> > res;        sort(candidates.begin(), candidates.end());        dfs(candidates, 0, target, cur, res);        return res;            }    void dfs(vector<int> &candidate, int start, int gap, vector<int> &cur, vector<vector<int> > &res) {        if (start == candidate.size()) {            return ;        }        if (gap == 0) {            res.push_back(cur);            return ;        }                for (int i = start; i < candidate.size(); i++) {            if (gap < candidate[i]) {                return ;            }            cur.push_back(candidate[i]);            dfs(candidate, i, gap-candidate[i], cur, res);            cur.pop_back();        }            }};


0 0
原创粉丝点击