LeetCode 40.Combination Sum II

题目:

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] 

分析与解答:比Conbination Sum复杂了一丢丢,加上一个条件来判断当前数字是否被采用即可。我原本的想法是每次递归从当前数的下一个开始即可(栈不为空的情况下),但这也还不够,因为[2,2,2] target = 4这个条件下会出现两组解,所以还需记录一下递归的循环中上次用了什么数,下次不用即可。

class Solution {
  public:
    vector<vector<int> > result;
    vector<vector<int> > combinationSum2(vector<int> &candidates, int target) {
        sort(candidates.begin(), candidates.end());
        vector<int> tempRes;
        dfs(candidates, tempRes, target, 0);
        return result;
    }
    void dfs(vector<int> &candidates, vector<int> &tempRes, int target, int start) {
        int num = -1,i = start;
        if(!tempRes.empty())
            i++;
        for(; i < candidates.size(); ++i) {
            if(candidates[i] == num)
                continue;
            num = candidates[i];
            if(candidates[i] == target) {
                tempRes.push_back(candidates[i]);
                result.push_back(tempRes);
                tempRes.pop_back();
                return ;
            }
            if(candidates[i] < target) {
                tempRes.push_back(candidates[i]);
                dfs(candidates, tempRes, target - candidates[i], i);
                tempRes.pop_back();
            }
        }
        return;
    }
};

你可能感兴趣的:(array,backtracking)