Write a function that takes an integer n and return all possible combinations of its factors.

  1. You may assume that n is always positive.
  2. Factors should be greater than 1 and less than n.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Input: 1
Output: []

Input: 37
Output:[]

Input: 12
Output:
[
[2, 6],
[2, 2, 3],
[3, 4]
]

Input: 32
Output:
[
[2, 16],
[2, 2, 8],
[2, 2, 2, 4],
[2, 2, 2, 2, 2],
[2, 4, 4],
[4, 8]
]

其实从上面看出,1, n都不能当作factors, 所以arr.size()至少是2: i.e. 递归终止的条件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public List<List<Integer>> getFactors(int n) {
List<List<Integer>> list = new ArrayList<>();
dfs(list, new ArrayList<>(), n, 2); // 1 < x < n
return list;
}

public void dfs(List<List<Integer>> list, List<Integer> arr, int n, int start) {
if (n == 1 && arr.size() > 1) list.add(new ArrayList<>(arr));
for (int i = start; i <= n; ++i) {
if (n % i == 0) {
arr.add(i);
dfs(list, arr, n / i, i);
arr.remove(arr.size() - 1);
}
}
}
}

也可以看出, factor combination实际上还是递归就完了,只不过-变成了/, 并没有必要先全排列所有的因子。