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:
- You may assume that n is always positive.
- Factors should be greater than 1 and less than n.
Examples:
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]]
算法:DFS。函数头:private void dfs(int target, int num, List<Integer> crt, List<List<Integer>> result)
不断拆解为小一点的继续需要整除的数字。从num的数字开始,试着加入能被target整除的那些数字,来递归dfs(target / i, i, crt, result); 最后达到让target变成1的目标。
细节:用target % i == 0否来判断是否能够整除。
class Solution { public List
> getFactors(int n) { List
> result = new ArrayList<>(); if (n <= 1) { return result; } dfs(n, 2, new ArrayList (), result); return result; } private void dfs(int target, int num, List crt, List
> result) { if (target == 1 && crt.size() > 1) { result.add(new ArrayList (crt)); return; } for (int i = num; i <= target; i++) { if (target % i != 0) { continue; } crt.add(i); dfs(target / i, i, crt, result); crt.remove(crt.size() - 1); } } }