Combination Sum

来源:互联网 发布:哪里有唐筛计算软件 编辑:程序博客网 时间:2024/06/06 01:32

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] 


思路:DFS方法,加上判断和,以及i递归的时候范围不是从i+1开始,而是从i开始。

class Solution {public:    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {                sort(candidates.begin(), candidates.end());          vector<vector<int> > result;        if (candidates.size() == 0) {            return result;        }                vector<int> v;        combinationUtil(result, candidates, v, 0, target);        return result;    }        void combinationUtil(vector<vector<int> > &result, vector<int> &candidates, vector<int> &v, int start, int sum) {        if (sum == 0) {            result.push_back(v);            return;        }                for (int i = start; i < candidates.size(); i++) {            if(candidates[i] <= sum){                 v.push_back(candidates[i]);                 combinationUtil(result, candidates, v, i, sum-candidates[i]);                 v.pop_back();            }            else {                break;            }        }    }};


0 0