leetcode Question 18: Combination Sum II

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 (a1a2, … , 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] 

Analysis:

The only difference between this problem and the previous one is each element can be used at most once.
We can change the recursive step to handle this.

Code(C++):

class Solution {
public:
    void dfs(vector<int> &num, int target, vector<vector<int> > &res, vector<int> &r,int st){
        if (target<0){
            return;
        }else{
            if (target==0){
                res.push_back(r);
            }else{
                int pre = -1;
                for (int i=st;i<num.size();i++){
                    if (num[i]!=pre){
                        r.push_back(num[i]);
                        dfs(num,target-num[i],res,r,i+1);
                        pre = num[i];
                        r.pop_back();
                    }
                }
            }
        }
    }
    
    vector<vector<int> > combinationSum2(vector<int> &num, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<vector<int> > res;
        if (num.size()==0){return res;}
        sort(num.begin(),num.end());
        vector<int> r;
        dfs(num,target,res,r,0);
        return res;
    }
};

Code(Python):

class Solution:
    def search(self, candidates, target, i, res, ress):
        if target < 0:
            return
        else:
            if target == 0:
                res.append(ress[:]) #It is important to use "ress[:]" instead of "ress"
            else:
                for j in xrange(i, len(candidates)):
                    if j==0 or candidates[j] != candidates[j-1]:
                        ress.append(candidates[j])
                        self.search(candidates, target-candidates[j], j+1, res, ress)
                        ress.pop(-1) #if use "ress", this will pop the elemtnes in res also
    
    # @param {integer[]} candidates
    # @param {integer} target
    # @return {integer[][]}
    def combinationSum2(self, candidates, target):
        res =[]
        ress = []
        self.search(sorted(candidates), target, 0, res, ress)
        return res
        

No comments:

Post a Comment