首页 > 代码库 > Combination Sum II -- leetcode

Combination Sum II -- leetcode

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

Each number in C may only be used once in the combination.

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 10,1,2,7,6,1,5 and target 8
A solution set is: 
[1, 7] 
[1, 2, 5] 
[2, 6] 
[1, 1, 6] 


此题目,candidates有重复的数字出现。

在leetcode上实际执行时间为23ms。


class Solution {
public:
    vector<vector<int> > combinationSum2(vector<int> &candidates, int target) {
        vector<vector<int> > result;

        sort(candidates.begin(), candidates.end());
        vector<int> solution;
        helper(result, solution, candidates, 0, target);
        return result;
    }

    void helper(vector<vector<int> >&result, vector<int> &solution, const vector<int> &candidates, int index, int target) {
        if (!target)
                result.push_back(solution);
        else if (target < 0)
                return;

        for (int i = index; i < candidates.size(); i++) {
                solution.push_back(candidates[i]);
                helper(result, solution, candidates, i+1, target-candidates[i]);
                solution.pop_back();

                while (i+1 < candidates.size() && candidates[i] == candidates[i+1]) i++;
        }
    }
};


Combination Sum II -- leetcode