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.
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]
]

分析

这题与第39题的不同点如下

  • 不能重复使用同一个数字,这一点可以在递归的时候将start参数不断提前来实现
  • 答案中的数字的顺序是从前面的数字往后的,所以在最后要将答案反转
  • candidates中可能会有重复的数字,所以枚举数字的时候要跳过已经枚举过的数字

实现

class Solution {
public:
    vector> combinationSum2(vector& candidates, int target) {
        vector> ans;
        sort(candidates.begin(), candidates.end());
        ans = solve(candidates, target, 0);
        for(int i=0; i> solve(vector& candidates, int target, int start) {
        vector> ans;
        for(int i=start; i> tmp;
                tmp = solve(candidates, target-candidates[i], i+1);
                for(auto v: tmp){
                    v.push_back(candidates[i]);
                    ans.push_back(v);
                }
            }
            while(i+1

思考

这里也删掉了第39题中没用的两行代码。总体来说这道题做得很舒服=_=。

你可能感兴趣的:(40. Combination Sum II)