题目链接: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 (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] 

这道题的要求是给定一组候选数字C和目标数字T,找到所有C中数字的组合,使其和为T。数字只可以选择1次。

备注:所有候选数字全为正数,要以非递减方式返回数字组合,结果不包含重复元素。

这道题和Combination Sum差不多,同样要求返回所有情况,同样是一个NP问题,同可以通过回溯方式,逐个找到所有情况。

不同之处是,这道题的候选数字里包含重复数字,而且每个数字只可以选择1次。因此,在递归处理的时候有些细节差别:

  1. 需要加入判重代码,即判断当前候选数字是否等于前一个。
  2. 递归的时候,应该从下一个候选数字开始,而不是当前的候选数字。

时间复杂度:O(???)

空间复杂度:O(nm)(结果数量)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution
{
    vector<vector<int> > vvi;
public:
    vector<vector<int> > combinationSum2(vector<int> &num, int target)
    {
        sort(num.begin(), num.end());
        
        vector<int> vi;
        combinationSum2(num, target, 0, vi);
        return vvi;
    }

private:
    void combinationSum2(vector<int> &num, int target, int i, vector<int> &vi)
    {
        if(target == 0)
        {
            vvi.push_back(vi);
            return;
        }

        for(int j = i; j < num.size(); ++ j)
        {
            if(target < num[j])
                break;
            
            if(j > i && num[j] == num[j - 1])
                continue;

            vi.push_back(num[j]);
            combinationSum2(num, target - num[j], j + 1, vi);
            vi.pop_back();
        }
    }
};