Skip to main content

[LeetCode Solution 40]: Combination Sum II


[LeetCode Solution 40]: Combination Sum II


*********************************************************************************

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 the target) will be positive integers.
  • 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]
]

--------------------------------------------------------------------------------------------------

Approach Recursive Method

Strategy
The idea is same with the [LeetCode Solution 39] Combination Sum, using backtracking method, but the only difference is how to get the value that we have to skip that can help us to avoid the duplication. Here is an example that gives you the idea:

For example:
We are going to deal the array \([1, 2, 2', 3, 5]\) and the target is \(7\) if we check the tree as the follows, we find that the blue branch and the green branch is doing the same stuff. 

So, how can we find the node that we want to skip, for example, we want to skip the green 2', not the blue 2'. We find that we have to add 2 constraints.


  1. When we find that the element adjacent are equal, candidnate[i] == candidnate[i-1];
  2. when the index of the element we visit is bigger than the start one. For example, the in example above, green 2' is visited after all the elements in blue 2 have been visited (the 1's 2nd turn to visited the green 2')

The modified code is as follows:

Java
class Solution {
 public List<List<Integer>> combinationSum2(int[] candidates, int target) {
  List<List<Integer>> res = new ArrayList<>();
  Arrays.sort(candidates);
  helper(candidates, target, 0, res, new ArrayList<>());
  return res;
 }

 public void helper(int[] candidates, int tar, int start, List<List<Integer>> res, List<Integer> temp) {
  if (tar < 0)
   return;
  else if (tar == 0)
   res.add(new ArrayList<>(temp));
  else {
   for (int i = start; i < candidates.length; i++) {
    if (candidates[i] > tar)
     break;
    if(i > start && candidates[i] == candidates[i-1]) continue; 
    temp.add(candidates[i]);
    helper(candidates, tar - candidates[i], i + 1, res, temp);
    temp.remove(temp.size() - 1);
   }
  }
 }
}
Complexity Analysis
  • Time complexity : \(O(2^n)\). where \(n\) is the number of elements in the array. Because we have to try all the \(n\) combinations
  • Space complexity : \(O(log(n))\). The space complexity is related to the height of the 'Tree' which is \(O(log(n))\)

The Running results:


Comments

Popular posts from this blog

[LeetCode Solution 230]: Kth Smallest Element in a BST

Question: Given a binary search tree, write a function  kthSmallest  to find the  k th smallest element in it. ************************************************************************************************************************************ Write Infront To read to a tutorial, please to read the tutorial of in-order traversal of BST, please check: LeetCode Solution 94: Binary Tree Inorder Traversal We are going to solve this question using the following 4 methods: ->Binary Search ->Recursive ->Iterative ->Morris  Approach #1 Binary Search [Accepted] Detail Explanation The first method to solve this problem is using Binary Search. The idea is very easy and extremely to think. We use BST's property that the left child of the root is smaller than the root while the right child of the root is always bigger. We consider that the root is the pivot, and find the number of the nodes in the left subtree and the number of the nodes in th

[LeetCode Solution 145] Binary Tree Postorder Traversal

[LeetCode Solution 145]: Binary Tree Postorder Traversal Question: Given a binary tree, return the  postorder  traversal of its nodes' values. For example: Given binary tree  {1,#,2,3} , 1 \ 2 / 3 return  [3,2,1] . Approach #1 Recursive [Accepted] Detail Explanation The first method to solve this problem is using recursive. This is the classical method and straightforward. we can define a helper function to implement recursion. The java code is as follows: Java public class Solution { public List<Integer> postorderTraversal (TreeNode root) { List<Integer> res = new ArrayList<>(); helper(root, res); return res; } public void helper (TreeNode root, List<Integer> res) { if (root != null ) { if (root.left != null ) { helper(root.left, res); } if (root.right != null ) { helper(root.right, res); } res.add(root.val); } } } Complexity Analysis Time complexity :

[Interview]: URLify

[Interview]  URLify: -------------------------------------------------------------------------------------------------------------------------- Question: URLify: Write a method to replace all spaces in a string with ‘%20’, you may assume that the string has sufficient space at the end to hold the additional characters. Example  input: ' mr john smith '  output: ' mr %20john%20smith' --------------------------------------------------------------------------------------------------------------------------   Idea 1:  Start from the back and start replacing until the character is not ' ', and replace the characters in reverse order. Solution 1: public class Solution{ public String replace(char[] str) { boolean flag = false; StringBuffer sb = new StringBuffer(); for (int i = str.length - 1; i >= 0; i--) { if (str[i] != ' ') flag = true; if (flag == true) { if (str[i] == ' ') { s