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: Each combination's factors must be sorted ascending, for example: The factors of 2 and 6 is [2, 6], not [6, 2]. 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, 直到 n == 1. 有个判断条件 if (item.size() > 1) 是为了防止答案是自己本身n, 按照题意, 这是不允许的.
参考了:http://www.meetqun.com/thread-10673-1-1.html
时间复杂度, 个人觉得是O(n*log(n)), 一开始觉得是O(n!), 但後来想想好像没那麽大. 我的想法是,
最一开始的for回圈是n, 但是一旦进入了下一个DFS, 每次最差都是 n / i在减小, 这边就是log(n), 所以总共是O(n*log(n)), 有错还请指正.
1 public class Solution { 2 public List<List<Integer>> getFactors(int n) { 3 List<List<Integer>> res = new ArrayList<List<Integer>>(); 4 List<Integer> item = new ArrayList<Integer>(); 5 if (n <= 3) return res; 6 helper(2, n, res, item); 7 return res; 8 } 9 10 public void helper(int start, int n, List<List<Integer>> res, List<Integer> item) { 11 if (n == 1) { 12 if (item.size() > 1) { 13 res.add(new ArrayList<Integer>(item)); 14 return; 15 } 16 } 17 for (int i=start; i<=n; i++) { 18 if (n%i == 0) { 19 item.add(i); 20 helper(i, n/i, res, item); 21 item.remove(item.size()-1); 22 } 23 } 24 } 25 }