天天看點

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