Tuesday, April 29, 2014

Combination Sum II -- Leetcode

Question:
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] 

Answer:
Using the code for Combination Sum, differentce:
1. just add while() loop code to avoid push the same element in a same level in DFS when pop back an element in a level.
2. for the further level, the start index should be (i+1) instead of (i), as each element can only be used once!

class Solution {
public:
    vector<vector<int> > combinationSum2(vector<int> &num, int target) {
        sort(num.begin(),num.end());
        vector<int> subres;
        vector<vector<int>> res;
        conbinationSumDFS(subres,res,num,0,target);
        return res;
    }
 
    void conbinationSumDFS(vector<int> &subres, vector<vector<int>> &res, vector<int> &num, int start, int sum){
        if(sum==0){
            res.push_back(subres);
            return;
        }
     
        for(int i= start; i< num.size();++i){
            if(num[i] <= sum){
                subres.push_back(num[i]);
                conbinationSumDFS(subres,res,num,i+1,sum-num[i]);   //Note the start index is i+1, for each ele can only be used once!
                subres.pop_back();
               
                while(i+1 < num.size() && num[i] == num[i+1]){    //To avoid push same element in a same level.
                    ++i;
                }
            }
            else
                break;
        }
        return;
    }
};

No comments:

Post a Comment