254 Factor Combinations

1. Question

Numbers can be regarded as product of its factors. For example,
1
8 = 2 x 2 x 2;
2
= 2 x 4.
Copied!
Write a function that takes an integernand return all possible combinations of its factors.
Note:
  1. 1.
    You may assume that n is always positive.
  2. 2.
    Factors should be greater than 1 and less than n.
Examples: input:1 output: []
input: 37
output: []
input:12
output:
1
[
2
[2, 6],
3
[2, 2, 3],
4
[3, 4]
5
]
Copied!
input:32
output:
1
[
2
[2, 16],
3
[2, 2, 8],
4
[2, 2, 2, 4],
5
[2, 2, 2, 2, 2],
6
[2, 4, 4],
7
[4, 8]
8
]
Copied!

2. Implementation

(1) Backtracking
1
class Solution {
2
public List<List<Integer>> getFactors(int n) {
3
List<List<Integer>> res = new ArrayList<>();
4
List<Integer> factors = new ArrayList<>();
5
recGetFactors(2, n, factors, res);
6
return res;
7
}
8
9
public void recGetFactors(int factor, int curNum, List<Integer> factors, List<List<Integer>> res) {
10
if (curNum == 1 && factors.size() > 1) {
11
res.add(new ArrayList<>(factors));
12
return;
13
}
14
15
for (int i = factor; i <= curNum; i++) {
16
if (curNum % i == 0) {
17
factors.add(i);
18
recGetFactors(i, curNum / i, factors, res);
19
factors.remove(factors.size() - 1);
20
}
21
}
22
}
23
}
Copied!

3. Time & Space Complexity

时间复杂度O((logn)! * n ^ (logn)),对于数n,它有大约logn个约数, 具体解析见https://www.jiuzhang.com/qa/5224/ 空间复杂度O(logn),等于约数的个数