Factor Combinations
Factor Combinations
Problem:
Numbers can be regarded as product of its factors. For example,
8 = 2 x 2 x 2; = 2 x 4.
Write a function that takes an integer n and return all possible combinations of its factors.
Note:
- Each combination's factors must be sorted ascending, for example: The factors of 2 and 6 is
[2, 6], not[6, 2]. - You may assume that n is always positive.
- Factors should be greater than 1 and less than n.
1 public class Solution { 2 public List<List<Integer>> getFactors(int n) { 3 List<List<Integer>> listAll = new ArrayList<>(); 4 if (n < 2) return listAll; 5 List<Integer> list = factors(n); 6 7 helper(n, 1, 0, list, listAll, new ArrayList<Integer>()); 8 return listAll; 9 } 10 11 public void helper(int n, long value, int index, List<Integer> list, List<List<Integer>> listAll, List<Integer> temp) { 12 if (index >= list.size() || value >= n) return; 13 14 int curValue = list.get(index); 15 temp.add(curValue); 16 value *= curValue; 17 18 if (n == value) { 19 listAll.add(new ArrayList<Integer>(temp)); 20 } 21 22 helper(n, value, index, list, listAll, temp); 23 value /= curValue; 24 temp.remove(temp.size() - 1); 25 helper(n, value, index + 1, list, listAll, temp); 26 } 27 28 public List<Integer> factors(int n) { 29 List<Integer> list = new ArrayList<>(); 30 for (int i = 2; i <= (n + 1) / 2; i++) { 31 if (n % i == 0) { 32 list.add(i); 33 } 34 } 35 return list; 36 } 37 }
上面代码其实可以用另下面这种方法,原理一样。
1 public class Solution { 2 public List<List<Integer>> getFactors(int n) { 3 List<List<Integer>> result = new ArrayList<>(); 4 List<Integer> list = new ArrayList<>(); 5 helper(2, 1, n, result, list); 6 return result; 7 } 8 9 public void helper(int start, int product, int n, List<List<Integer>> result, List<Integer> curr) { 10 if (start > n || product > n) return; 11 12 if (product == n) { 13 List<Integer> t = new ArrayList<>(curr); 14 result.add(t); 15 } 16 17 for (int i = start; i <= n / 2; i++) { 18 if(i * product > n) break; 19 if (n % i == 0) { 20 curr.add(i); 21 helper(i, i * product, n, result, curr); 22 curr.remove(curr.size() - 1); 23 } 24 } 25 } 26 }

浙公网安备 33010602011771号