Advertisement
1988coder

78. Subsets

Jan 2nd, 2019
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.31 KB | None | 0 0
  1. /**
  2.  * Backtracking (Recursion)
  3.  *
  4.  * T(n) = 0 × (n C 0) + 1 × (n C 1) + 2 × (n C 2) + … + n × (n C n)
  5.  *
  6.  * Note that (n C k) = (n C n-k). Therefore:
  7.  *
  8.  * T(n) = 0 × (n C n) + 1 × (n C n-1) + 2 × (n C n-2) + … + n × (n C 0)
  9.  *
  10.  * If we add these two together, we get
  11.  *
  12.  * 2T(n) = n × (n C 0) + n × (n C 1) + … + n × (n C n)
  13.  *
  14.  * = n × (n C 0 + n C 1 + … + n C n)
  15.  *
  16.  * As per binomial theorem, (n C 0 + n C 1 + … + n C n) = 2^n, so
  17.  *
  18.  * 2*T(n) = n * 2^n => T(n) = n * 2^(n-1) = O(n * 2^n)
  19.  *
  20.  * Time Complexity: O(N * 2 ^ N) Refer https://stackoverflow.com/a/20711498
  21.  *
  22.  * Space Complexity: O(N) (Excluding the result space)
  23.  *
  24.  * N = Length of input nums array
  25.  */
  26. class Solution {
  27.     public List<List<Integer>> subsets(int[] nums) {
  28.         List<List<Integer>> result = new ArrayList();
  29.         if (nums == null) {
  30.             return result;
  31.         }
  32.         if (nums.length == 0) {
  33.             result.add(new ArrayList());
  34.             return result;
  35.         }
  36.  
  37.         backtrack(result, new ArrayList<Integer>(), nums, 0);
  38.  
  39.         return result;
  40.     }
  41.  
  42.     private void backtrack(List<List<Integer>> list, List<Integer> tempList, int[] nums, int start) {
  43.         list.add(new ArrayList<Integer>(tempList));
  44.         for (int i = start; i < nums.length; i++) {
  45.             tempList.add(nums[i]);
  46.             backtrack(list, tempList, nums, i + 1);
  47.             tempList.remove(tempList.size() - 1);
  48.         }
  49.     }
  50. }
  51.  
  52. /**
  53.  * Iterative Solution
  54.  *
  55.  * Time Complexity: O(N * 2 ^ N) Refer https://stackoverflow.com/a/20711498
  56.  *
  57.  * Space Complexity: O(1) (Excluding the result space)
  58.  *
  59.  * N = Length of input nums array
  60.  */
  61. class Solution {
  62.     public List<List<Integer>> subsets(int[] nums) {
  63.         List<List<Integer>> result = new ArrayList();
  64.         if (nums == null) {
  65.             return result;
  66.         }
  67.         result.add(new ArrayList<Integer>());
  68.         if (nums.length == 0) {
  69.             return result;
  70.         }
  71.  
  72.         for (int num : nums) {
  73.             int listSize = result.size();
  74.             for (int j = 0; j < listSize; j++) {
  75.                 List<Integer> tempList = new ArrayList<Integer>(result.get(j));
  76.                 tempList.add(num);
  77.                 result.add(tempList);
  78.             }
  79.         }
  80.  
  81.         return result;
  82.     }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement