LeetCode 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, a1a2 ≤ … ≤ 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]


 Need to pay special attention to the condition that "The number can be used repeatedly", we thus use a pointer to pointer to the value used and not adding one when being used in the next level.


#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

void combinationSum(vector<int>& candidates, int start, vector< vector<int> >& res, vector<int>& path, int& sum, int target) {
    if(sum > target) return;
    if(sum == target) {
        res.push_back(path);
    }
    for(int i = start; i < candidates.size(); ++i) {
        sum += candidates[i];
        path.push_back(candidates[i]);
        combinationSum(candidates, i, res, path, sum, target);
        path.pop_back();
        sum -= candidates[i];
    }
}

vector< vector<int> > combinationSum(vector<int>& candidates, int target) {
    vector< vector<int> > res;
    vector<int> path;
    sort(candidates.begin(), candidates.end());
    int sum = 0;
    combinationSum(candidates, 0,  res, path, sum, target);
    return res;
}

int main(void) {
    vector<int> candidates{2, 3, 6, 7};
    vector< vector<int> > res = combinationSum(candidates, 7);
    for(int i = 0; i < res.size(); ++i) {
        for(int j = 0; j < res[0].size(); ++j) {
            cout << res[i][j] << endl;
        }
        cout << endl;
    }
}



你可能感兴趣的:(LeetCode 39. Combination Sum)