标签:
题目:
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:
[2, 6]
, not [6, 2]
.
Examples:
input: 1
output:
[]input:
37
[]input:
12
[ [2, 6], [2, 2, 3], [3, 4] ]input:
32
[ [2, 16], [2, 2, 8], [2, 2, 2, 4], [2, 2, 2, 2, 2], [2, 4, 4], [4, 8] ]
题解:
求一个数的所有factor,这里我们又想到了DFS + Backtracking, 需要注意的是,factor都是>= 2的,并且在此题里,这个数本身不能算作factor,所以我们有了当n <= 1时的判断 if(list.size() > 1) add the result to res.
Time Complexity - O(2n), Space Complexity - O(n).
public class Solution { public List<List<Integer>> getFactors(int n) { List<List<Integer>> res = new ArrayList<>(); List<Integer> list = new ArrayList<>(); getFactors(res, list, n, 2); return res; } private void getFactors(List<List<Integer>> res, List<Integer> list, int n, int factor) { if(n <= 1) { if(list.size() > 1) res.add(new ArrayList<Integer>(list)); return; } for(int i = factor; i <= n; i++) { if(n % i == 0) { list.add(i); getFactors(res, list, n / i, i); list.remove(list.size() - 1); } } } }
Reference:
标签:
原文地址:http://www.cnblogs.com/yrbbest/p/5014873.html