[LeetCode]40 和的组合 II

Combination Sum II(和的组合 II)

【难度:Medium】
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 (a1, a2, … , 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]
LeetCode 39题的延伸,在39题的基础上增加了数组有重复数字这一情况,并且不允许出现重复的答案组合。


解题思路

有了39题的经验,此题同样可以沿用39题的解法——回溯来解决,要考虑的是如何避免重复。如果使用39题的代码会发现有两个相同的组合[1,7]和[7,1],所以只要解决了去重的问题即可。


c++代码如下:

class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        vector<vector<int>> ans;
        vector<int> tmp;
        if (candidates.empty())
            return ans;
        quicksort(candidates,0,candidates.size()-1);
        if (target < candidates[0])
            return ans;
        tranverse(ans,candidates,tmp,target,0);
        return ans;
    }
    void quicksort(vector<int>& n, int low, int high) {
        if (low >= high)
            return;
        int i = low;
        int j = high;
        int k = n[low];
        while (i < j) {
            while (i < j && n[j] >= k)
                j--;
            n[i] = n[j];
            while (i < j && n[i] <= k)
                i++;
            n[j] = n[i];
        }
        n[i] = k;
        quicksort(n,low,i-1);
        quicksort(n,i+1,high);
    }
    void tranverse(vector<vector<int>>& ans, vector<int> n, vector<int>& tmp, int t, int index) {
        if (t == 0) {
            ans.push_back(tmp);
            return;
        }
        for (int i = index; i < n.size(); i++) {
            if (t < n[i])
                break;
            /*去重的判断在于i == index || n[i] != n[i-1]*/

            if ((t == n[i] || t >= 2*n[i]) && (i == index || n[i] != n[i-1])) {
                tmp.push_back(n[i]);
                tranverse(ans,n,tmp,t-n[i],i+1);
                tmp.pop_back();
            }
        }
        return;
    }

};

你可能感兴趣的:(LeetCode)