Advertisement
1988coder

254. Factor Combinations

Jan 16th, 2019
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.26 KB | None | 0 0
  1.  
  2. // LeetCode URL: https://leetcode.com/problems/factor-combinations/
  3.  
  4. import java.util.ArrayList;
  5. import java.util.List;
  6.  
  7. /**
  8.  * Backtrackking (with optimization)
  9.  *
  10.  * Time Complexity: Refer: https://stackoverflow.com/a/45664178
  11.  *
  12.  * O(N * log(sqrt(N)) + sqrt(N))
  13.  *
  14.  * Space Complexity: O(sqrt(N))
  15.  */
  16. class Solution {
  17.     public List<List<Integer>> getFactors(int n) {
  18.         List<List<Integer>> result = new ArrayList<>();
  19.         if (n <= 3) {
  20.             return result;
  21.         }
  22.  
  23.         getFactorsHelper(result, new ArrayList<Integer>(), n, 2);
  24.         return result;
  25.     }
  26.  
  27.     private void getFactorsHelper(List<List<Integer>> list, List<Integer> tempList, int n, int start) {
  28.         if (n == 1) {
  29.             if (tempList.size() > 1) {
  30.                 list.add(new ArrayList<Integer>(tempList));
  31.             }
  32.             return;
  33.         }
  34.  
  35.         for (int i = start; i * i <= n; i++) {
  36.             if (n % i != 0) {
  37.                 continue;
  38.             }
  39.             tempList.add(i);
  40.             getFactorsHelper(list, tempList, n / i, i);
  41.             tempList.remove(tempList.size() - 1);
  42.         }
  43.  
  44.         tempList.add(n);
  45.         getFactorsHelper(list, tempList, 1, n);
  46.         tempList.remove(tempList.size() - 1);
  47.     }
  48. }
  49.  
  50. /**
  51.  * Backtrackking (without optimization)
  52.  *
  53.  * Time Complexity: Refer: https://stackoverflow.com/a/45664178
  54.  *
  55.  * O(N * log(N) + N)
  56.  *
  57.  * Space Complexity: O(N)
  58.  */
  59. class Solution2 {
  60.     public List<List<Integer>> getFactors(int n) {
  61.         List<List<Integer>> result = new ArrayList<>();
  62.         if (n <= 3) {
  63.             return result;
  64.         }
  65.  
  66.         getFactorsHelper(result, new ArrayList<Integer>(), n, 2);
  67.         return result;
  68.     }
  69.  
  70.     private void getFactorsHelper(List<List<Integer>> list, List<Integer> tempList, int n, int start) {
  71.         if (n == 1) {
  72.             if (tempList.size() > 1) {
  73.                 list.add(new ArrayList<Integer>(tempList));
  74.             }
  75.             return;
  76.         }
  77.  
  78.         for (int i = start; i <= n; i++) {
  79.             if (n % i != 0) {
  80.                 continue;
  81.             }
  82.             tempList.add(i);
  83.             getFactorsHelper(list, tempList, n / i, i);
  84.             tempList.remove(tempList.size() - 1);
  85.         }
  86.     }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement