|
| 1 | +package backtracking; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Arrays; |
| 5 | +import java.util.List; |
| 6 | + |
| 7 | +// https://leetcode.com/problems/factor-combinations/ |
| 8 | +public class FactorCombinations { |
| 9 | + |
| 10 | + public static void main(String[] args) { |
| 11 | + FactorCombinations obj = new FactorCombinations(); |
| 12 | + int n = 12; |
| 13 | + List<List<Integer>> resultList = obj.getFactors(12); |
| 14 | + System.out.println(Arrays.toString(resultList.toArray())); |
| 15 | + } |
| 16 | + |
| 17 | + public List<List<Integer>> getFactors(int n) { |
| 18 | + List<List<Integer>> resultList = new ArrayList<List<Integer>>(); |
| 19 | + // DFS |
| 20 | + //dfs(resultList, new ArrayList<Integer>(), n, 2); |
| 21 | + dfs1(resultList, new ArrayList<Integer>(), n, 2); |
| 22 | + |
| 23 | + return resultList; |
| 24 | + } |
| 25 | + |
| 26 | + private void dfs(List<List<Integer>> resultList, List<Integer> list, int n, int start) { |
| 27 | + // exit |
| 28 | + if (n == 1) { |
| 29 | + if (list.size() > 1) { |
| 30 | + resultList.add(new ArrayList<Integer>(list)); |
| 31 | + } |
| 32 | + |
| 33 | + return; |
| 34 | + } |
| 35 | + |
| 36 | + for (int i = start; i <= n; i++) { |
| 37 | + if (n % i == 0) { |
| 38 | + list.add(i); |
| 39 | + dfs(resultList, list, n / i, i); |
| 40 | + |
| 41 | + list.remove(list.size() - 1); |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + |
| 47 | + private void dfs1(List<List<Integer>> resultList, List<Integer> list, int n, int start) { |
| 48 | + for (int i = start; i * i < n; i++) { |
| 49 | + if (n % i == 0) { |
| 50 | + List<Integer> newList = new ArrayList<Integer>(list); |
| 51 | + newList.add(i); |
| 52 | + dfs1(resultList, newList, n / i, i); |
| 53 | + |
| 54 | + newList.add(n / i); |
| 55 | + resultList.add(new ArrayList<Integer>(newList)); |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | +} |
0 commit comments