天天看点

[ LeetCode ] #40. Combination Sum II(数列组合2)

题目:40. Combination Sum II

Given a collection of candidate numbers (

candidates

) and a target number (

target

), find all unique combinations in 

candidates

 where the candidate numbers sums to 

target

.

Each number in 

candidates

 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.

Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]
           

Example 2:

Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
  [1,2,2],
  [5]
]
           

题意:

此题与上一题相差无异。给定一个数列

candidates

和一个整数target,数列中所有值保证大于零,且允许有重复值。求出使用所给数列中的值(每个值仅能使用一次,假如所给数列包含两个1,则1可以使用两次)之和为target的所有不重复组合。

分析:

同39题一样,使用回漱解决即可,不过这里不允许数值多次重复使用,因此,每次回漱的起始坐标为当前坐标的下一个即可,另外 由于数列中可能包含重复值,所以 这里为了简化每次处理之后都将跳过所有与当前值重复的元素。

Code

class Solution {
public:
    vector<vector<int>> ans;
        vector<int> tmp;
        void getSum(vector<int>&num, int idx, int target){
            if(0==target){
                ans.push_back(tmp);
                return ;
            }
            for(int i=idx;i<num.size();++i){
                if(num[i]<=target){
                    tmp.push_back(num[i]);
                    getSum(num, i+1, target-num[i]);
                    tmp.pop_back();
                }else{
                    break;
                }
                while(i<num.size()-1 && num[i]==num[i+1])++i; 
            }
    }
    vector<vector<int>> combinationSum2(vector<int>& num, int target) {
        sort(num.begin(),num.end());
        getSum(num, 0, target);
        return ans;
    }
};
           

Result:

Runtime: 8 ms, faster than 100.00% of C++ online submissions for Combination Sum II.

Memory Usage: 10.2 MB, less than 55.93% of C++ online submissions forCombination Sum II.