Advertisement
1988coder

491. Increasing Subsequences

Jan 4th, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.85 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.HashSet;
  3. import java.util.LinkedList;
  4. import java.util.List;
  5.  
  6. /**
  7.  * Backtracking (Recursion). Very similar to Subsets II
  8.  *
  9.  * T(n) = 0 × (n C 0) + 1 × (n C 1) + 2 × (n C 2) + … + n × (n C n)
  10.  *
  11.  * Note that (n C k) = (n C n-k). Therefore:
  12.  *
  13.  * T(n) = 0 × (n C n) + 1 × (n C n-1) + 2 × (n C n-2) + … + n × (n C 0)
  14.  *
  15.  * If we add these two together, we get
  16.  *
  17.  * 2T(n) = n × (n C 0) + n × (n C 1) + … + n × (n C n)
  18.  *
  19.  * = n × (n C 0 + n C 1 + … + n C n)
  20.  *
  21.  * As per binomial theorem, (n C 0 + n C 1 + … + n C n) = 2^n, so
  22.  *
  23.  * 2*T(n) = n * 2^n => T(n) = n * 2^(n-1) = O(n * 2^n)
  24.  *
  25.  * Time Complexity: O(N * 2 ^ N) Refer https://stackoverflow.com/a/20711498
  26.  *
  27.  * Space Complexity: O(N) (Excluding the result space)
  28.  *
  29.  * N = Length of input nums array
  30.  */
  31. class Solution {
  32.     public List<List<Integer>> findSubsequences(int[] nums) {
  33.         List<List<Integer>> result = new ArrayList<>();
  34.         if (nums == null || nums.length < 2) {
  35.             return result;
  36.         }
  37.  
  38.         backtrack(result, new LinkedList<Integer>(), nums, 0);
  39.  
  40.         return result;
  41.     }
  42.  
  43.     private void backtrack(List<List<Integer>> result, LinkedList<Integer> tempList, int[] nums, int start) {
  44.         if (tempList.size() > 1) {
  45.             result.add(new ArrayList<Integer>(tempList));
  46.         }
  47.         HashSet<Integer> numsUsed = new HashSet<>();
  48.         for (int i = start; i < nums.length; i++) {
  49.             if (numsUsed.contains(nums[i])) {
  50.                 continue;
  51.             }
  52.             numsUsed.add(nums[i]);
  53.             if (tempList.size() > 0 && tempList.getLast() > nums[i]) {
  54.                 continue;
  55.             }
  56.             tempList.add(nums[i]);
  57.             backtrack(result, tempList, nums, i + 1);
  58.             tempList.removeLast();
  59.         }
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement