LeetCode 40 - Combination Sum II


Related: LeetCode 39 - Combination Sum
Leetcode 216 Combination Sum III
LeetCode 377 - Combination Sum IV
Given a collection of candidate numbers C and a target number T, find all unique combinations in C where the candidate numbers sums to TEach number in C may only be used once in the combination.
  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1,a2,,ak) must be in non-descending order. (i.e., a1a2ak ).
  • 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] }
Almost the same as last problem LeetCode 39 - Combination Sum
Difference: 
1. Element can only be used once and may have duplicated elements.
Tips:
1. The index for next level will be current index+1;
2. To avoid duplicated results: make sure if the iteration pointer i is not the start index, it will skip the duplicated element. Note: always execute the first loop(i==start).
eg. 2,2,2,3 target =7, the recursion tree will look like this:
2,2,2,3--> 2,2,3 --> 2,3, Notice: during the recursion, we skipped several 2,2,3 and 2,3
https://discuss.leetcode.com/topic/44037/combination-sum-i-ii-and-iii-java-solution-see-the-similarities-yourself/
https://discuss.leetcode.com/topic/19845/java-solution-using-dfs-easy-understand
[1,1,1]
Let's think when should we skip the third 1, only when we add the first 1 but has not added the second 1, which implies that we only need to use one "1", rather than two "1", so skip the third "1".
If we need to use two or three "1", the second "1" is used, then the third "1" won't be skipped .
As for your concern, if the first and second "1" are selected, do we skip the third ? of course not, because we may use three "1".

public ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        if (num == null || num.length == 0)
            return result;
        Arrays.sort(num);       // Sort the candidate in non-descending order
        ArrayList<Integer> current = new ArrayList<Integer>();
        recursiveAppend(num, target, 0, current, result);
        return result;
    }
    private void recursiveAppend(int[] num, int target, int startIndex, ArrayList<Integer> current,
                                 ArrayList<ArrayList<Integer>> result) {
        if (target < 0)
            return;
        if (target == 0) {     // The current array is an solution
            result.add(new ArrayList<Integer>(current));
            return;
        }
        for (int i = startIndex; i < num.length; i++) {
            if (num[i] > target)    // No need to try the remaining candidates
                break;
            if (i > startIndex && num[i] == num[i-1])//\\
                // The same number has been added earlier within the loop
                continue;
            // Add candidate[i] to the current array
            current.add(num[i]);
            // Recursively append the current array to compose a solution
            recursiveAppend(num, target-num[i], i+1, current, result);
            // Remove candidate[i] from the current array, and try next candidate in the next loop
            current.remove(current.size()-1);
        }
    }
https://discuss.leetcode.com/topic/44037/combination-sum-i-ii-and-iii-java-solution-see-the-similarities-yourself
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
   List<List<Integer>> list = new LinkedList<List<Integer>>();
   Arrays.sort(candidates);
   backtrack(list, new ArrayList<Integer>(), candidates, target, 0);
   return list;
}

private void backtrack(List<List<Integer>> list, List<Integer> tempList, int[] cand, int remain, int start) {
   
   if(remain < 0) return; /** no solution */
   else if(remain == 0) list.add(new ArrayList<>(tempList));
   else{
      for (int i = start; i < cand.length; i++) {
         if(i > start && cand[i] == cand[i-1]) continue; /** skip duplicates */
         tempList.add(cand[i]);
         backtrack(list, tempList, cand, remain - cand[i], i+1);
         tempList.remove(tempList.size() - 1);
      }
   }
}
https://discuss.leetcode.com/topic/34364/java-solutions-beats-99-87
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> results = new ArrayList<>();
        calcCombinationSum2(candidates, 0, new int[candidates.length], 0, target, results);
        return results;
    }
    
    private void calcCombinationSum2(int[] candidates, int cindex, int[] list, int lindex, int target, List<List<Integer>> results) {
        if (target == 0) {
            List<Integer> result = new ArrayList<>();
            for (int i = 0; i < lindex; i++) {
                result.add(list[i]);
            }
            results.add(result);
            return;
        }
        
        int prev = 0;
        for (int i = cindex; i < candidates.length; i++) {
            if (candidates[i] != prev) {
                if (target - candidates[i] < 0) {
                    break;
                }
                
                list[lindex] = candidates[i];
                calcCombinationSum2(candidates, i + 1, list, lindex + 1, target - candidates[i], results);
                prev = candidates[i];
            }
        }
    }

http://codeganker.blogspot.com/2014/03/combination-sum-ii-leetcode.html
在这里我们还是需要在每一次for循环前做一次判断,因为虽然一个元素不可以重复使用,但是如果这个元素重复出现是允许的,但是为了避免出现重复的结果集,我们只对于第一次得到这个数进行递归,接下来就跳过这个元素了,因为接下来的情况会在上一层的递归函数被考虑到,这样就可以避免重复元素的出现
http://noalgo.info/935.html
由于可能出现相同元素,先排序方便后续处理。dfs时每次处理一个数字,相同的数字一起处理,相同数字可以不选,也可以每次选择一个,但不能选择超过其出现次数的个数。
http://www.jiuzhang.com/solutions/combination-sum-ii/
    private ArrayList<ArrayList<Integer>> results;

    public ArrayList<ArrayList<Integer>> combinationSum2(int[] candidates,
            int target) {
        if (candidates.length < 1) {
            return results;
        }

        ArrayList<Integer> path = new ArrayList<Integer>();
        java.util.Arrays.sort(candidates);
        results = new ArrayList<ArrayList<Integer>> ();
        combinationSumHelper(path, candidates, target, 0);

        return results;
    }

    private void combinationSumHelper(ArrayList<Integer> path, int[] candidates, int sum, int pos) {
        if (sum == 0) {
            results.add(new ArrayList<Integer>(path));
        }

        if (pos >= candidates.length || sum < 0) {
            return;
        }

        int prev = -1;
        for (int i = pos; i < candidates.length; i++) {
            if (candidates[i] != prev) {
                path.add(candidates[i]);
                combinationSumHelper(path, candidates, sum - candidates[i], i + 1);
                prev = candidates[i];
                path.remove(path.size()-1);
            }
        }
    }
X. DP
https://discuss.leetcode.com/topic/5777/dp-solution-in-python
I also did it with recursion, turns out the DP solution is 3~4 times faster.
def combinationSum2(self, candidates, target):
    candidates.sort()
    table = [None] + [set() for i in range(target)]
    for i in candidates:
        if i > target:
            break
        for j in range(target - i, 0, -1):
            table[i + j] |= {elt + (i,) for elt in table[j]}
        table[i].add((i,))
    return map(list, table[target])

X. Iterative - DFS
http://siyang2leetcode.blogspot.com/2015/03/combination-sum-ii.html
   class SumNode{  
     int index;  
     int sum;  
     List<Integer> path;  
     SumNode(int index, int value, List<Integer> path){  
       this.index = index;  
       this.sum = value;  
       this.path = new ArrayList<Integer>(path);  
     }  
     public void addNumber(int value){  
       this.sum += value;  
       this.path.add(value);  
     }  
   }  
   public List<List<Integer>> combinationSum2(int[] num, int target) {  
     List<List<Integer>> rslt = new ArrayList<List<Integer>>();  
     Set<List<Integer>> set = new HashSet<List<Integer>>();  
     Stack<SumNode> stack = new Stack<SumNode>();  
     Arrays.sort(num);  
     SumNode root = new SumNode(-1, 0, new ArrayList<Integer>());  
     stack.push(root);  
     while(!stack.isEmpty()){  
       SumNode node = stack.pop();  
       for(int i = node.index+1;i < num.length;i++){  
         if(node.sum + num[i] > target) break;  
         SumNode child = new SumNode(i, node.sum, node.path);  
         child.addNumber(num[i]);  
         if(child.sum==target) set.add(child.path);  
         else stack.push(child);  
       }  
     }  
     rslt.addAll(set);  
     return rslt;  
   }
X. Iterative Version: BFS Queue
http://siyang2leetcode.blogspot.com/2015/03/combination-sum-ii.html
 public class Solution {  
   class SumNode{  
     int index;  
     int sum;  
     List<Integer> path;  
     SumNode(int index, int value, List<Integer> path){  
       this.index = index;  
       this.sum = value;  
       this.path = new ArrayList<Integer>(path);  
     }  
     public void addNumber(int value){  
       this.sum += value;  
       this.path.add(value);  
     }  
   }  
   public List<List<Integer>> combinationSum2(int[] num, int target) {  
     List<List<Integer>> rslt = new ArrayList<List<Integer>>();  
     Set<List<Integer>> set = new HashSet<List<Integer>>();  
     Queue<SumNode> queue = new LinkedList<SumNode>();  
     Arrays.sort(num);  
     SumNode root = new SumNode(-1, 0, new ArrayList<Integer>());  
     queue.add(root);  
     while(!queue.isEmpty()){  
       SumNode node = queue.poll();  
       for(int i = node.index+1;i < num.length;i++){  
         if(node.sum + num[i] > target) break;  
         SumNode child = new SumNode(i, node.sum, node.path);  
         child.addNumber(num[i]);  
         if(child.sum==target) set.add(child.path);  
         else queue.add(child);  
       }  
     }  
     rslt.addAll(set);  
     return rslt;  
   }  
 }  
X. DFS Stack
   class SumNode{  
     int index;  
     int sum;  
     List<Integer> path;  
     SumNode(int index, int value, List<Integer> path){  
       this.index = index;  
       this.sum = value;  
       this.path = new ArrayList<Integer>(path);  
     }  
     public void addNumber(int value){  
       this.sum += value;  
       this.path.add(value);  
     }  
   }  
   public List<List<Integer>> combinationSum2(int[] num, int target) {  
     List<List<Integer>> rslt = new ArrayList<List<Integer>>();  
     Set<List<Integer>> set = new HashSet<List<Integer>>();  
     Stack<SumNode> stack = new Stack<SumNode>();  
     Arrays.sort(num);  
     SumNode root = new SumNode(-1, 0, new ArrayList<Integer>());  
     stack.push(root);  
     while(!stack.isEmpty()){  
       SumNode node = stack.pop();  
       for(int i = node.index+1;i < num.length;i++){  
         if(node.sum + num[i] > target) break;  
         SumNode child = new SumNode(i, node.sum, node.path);  
         child.addNumber(num[i]);  
         if(child.sum==target) set.add(child.path);  
         else stack.push(child);  
       }  
     }  
     rslt.addAll(set);  
     return rslt;  
   } 
Improved Way: Can I apply iterative method without using extra class (SumNode in the above code).
If I directly use List<Integer> as nodes, I need to find a way to store the sum of the list and the current index.  I could use the first element to store the sum, the second element to store the current index.
   public List<List<Integer>> combinationSum2(int[] num, int target) {  
     List<List<Integer>> rslt = new ArrayList<List<Integer>>();  
     Set<List<Integer>> set = new HashSet<List<Integer>>();  
     Stack<List<Integer>> stack = new Stack<List<Integer>>();  
     Arrays.sort(num);  
     // initial list  
     List<Integer> root = new ArrayList<Integer>();  
     root.add(0);  
     root.add(-1);  
     // DFS  
     stack.push(root);  
     while(!stack.isEmpty()){  
       List<Integer> list = stack.pop();  
       // check if target found  
       if(list.get(0)==target){  
         List<Integer> path = new ArrayList<Integer>();  
         for(int i = 0;i < list.size()-2;i++)  
           path.add(list.get(i+2));  
         set.add(path);  
       }  
       // push child list  
       for(int i = list.get(1)+1;i < num.length;i++){  
         if(list.get(0)+num[i] > target) break;  
         List<Integer> path = new ArrayList<Integer>(list);  
         path.set(0, path.get(0)+num[i]);  
         path.set(1, i);  
         path.add(num[i]);  
         stack.push(path);  
       }  
     }  
     rslt.addAll(set);  
     return rslt;   
   }  
X.
http://www.programmeronrails.com/2015/11/14/coding-problem-combination-sum-ii/
Create two many lists - some lists are invalid and discarded.
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
  List<List<Integer>> results = new LinkedList<List<Integer>>();  
  // sort the candidates
  Arrays.sort(candidates);

  // collect possible candidates from small to large.
  find(new ArrayList<Integer>(), target, candidates, 0, results);
  return results;
}

private void find(List<Integer> list, int target, int[] candidates, int index, List<List<Integer>> results) {

  if (target == 0) {
    results.add(list);
    return;
  }

  for (int i=index; i < candidates.length; i++) {
   
    // to avoid duplicate results by skipping the
    // candidate with the same value
    if(i>index && candidates[i] == candidates[i-1])
      continue;
   
    int newTarget = target - candidates[i];
    if (newTarget >= 0) {
      List<Integer> copy = new ArrayList<Integer>(list);
      copy.add(candidates[i]);
   
      // as the candidate could not be selected again,
      // the next candidate available is candidates[i+1]
      find(copy, newTarget, candidates, i+1, results);
   
    } else {
      break;
    }
  }
}
http://shanjiaxin.blogspot.com/2014/02/combination-sum-ii-leetcode.html
Change target to maintain remaining target.
public static ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) {
  Arrays.sort(num);
  ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
  ArrayList<Integer> list = new ArrayList<Integer>();
  combinationSumHelper(result, list, num, target, 0);
  return result;
}
private static void combinationSumHelper(ArrayList<ArrayList<Integer>> result,
    ArrayList<Integer> list, int[] num, int target, int position) {
  int sum = 0;
  for (int x: list) {
    sum += x;
  }
  if (sum == target) {
    result.add(new ArrayList<Integer>(list));
    return;
  }
  if (sum < target) {
    for (int i = position; i<num.length; i++) {
      if ( i != position && num[i] == num[i-1]) {
        continue;
      }

      list.add(num[i]);
      combinationSumHelper(result, list, num, target, i+1);
      list.remove(list.size() - 1);
    }
  }
}
http://bangbingsyb.blogspot.com/2014/11/leetcode-combination-sum-i-ii.html

https://discuss.leetcode.com/topic/60535/understanding-the-differences-between-the-dp-solution-and-simple-recursive-which-one-is-really-better
DP Solution:
  1. Start by creating an array of [target+1]. Call it arr.
  2. Initialize value at arr[candidates[i]] to be a set only containing {candidates[i]}.
  3. If there are any other indices j of arr that are non-empty, populate the arr[j+candidates[i]] with the set of arr[j] + candidates[i].
Good for:
If target is relatively small, and/or numbers in candidates are very dense.
O(M*N) where M is target, and N is candidates.size()
Recursive Solution:
  1. Start by recursing with an empty set on every element.
  2. DFS by adding the ith element on the temporary vector, calling the recursive function with the ith element added, then remove it.
  3. When the remaining is 0(we subtract target by candidate[i] every recursive call to candidate[i]), we add the result into the vector<vector<int>>.
Good for:
If M is overwhelmingly large.
Read full article from LeetCode - Combination Sum II | Darren's Blog

Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts