Tuesday, July 1, 2014

[Leetcode] Combination Sum

Problem 

Given a collection (or Set) of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
I. Each number in C may be used as many times as you want
II. Each number in C may only be used once in the combination.
For example,
Input: C = [2,3,6,7], T = 7
Output I : [2,2,3], [7]
Output II: [7]

Algorithms

Subset-like Problem.

A template to solve such subset-like problem. 

void helper(List<List<T>> res, List<T> cur, List<E> source, int index, ...){
    if(exceed boundary condition) return;
    if(valid solution) {res.add(cur); return;}
    For each possible choice without potential duplicates
            recursively solve remaining subproblem
    EndFor
}

Note, this approach has many duplicate solutions. 
  1. not including this one, index++
  2. including this one, index unchanged // we want include more current
  3. including this one, index++//done with this one, go to next one.

For example, C = [3,6], T = 6, and it should only have two solutions.
                             (index, target) =    (0,6)
                                                           /|\
                                      (1,6)           (0,3)                     (1,3)
                                        /|\                 /|\                           /|\
                          (2,6)  (1,0) (2,0)     (1,3) (1,0) (2,0)      (2,3) (1,-3) (2,-3)
However, we have four solutions.
The algorithm below can eliminate the duplicate solutions.
for(int i=index;i<C.length;i++){
     if(C[i] > target) break;
     list.add(C[i]);
     helper(C,i,target - C[i],list,lists,level+1);
     list.remove(list.size()-1);

}

                           (list, index,target) = (null, 0, 6)
                                                    /\
                                ([3], 0, 3)               ([6],1, 0)
                                     /\
                    ([3,3],0, 0)      



Code



No comments:

Post a Comment