1 public class Solution { 2 public List<List<Integer>> getFactors(int n) { 3 List<List<Integer>> result = new ArrayList<List<Integer>>(); 4 if (n <= 1) { 5 return result;//负数如何处理,返回值还是抛异常与面试官讨论 6 } 7 List<Integer> path = new ArrayList<Integer>(); 8 findFactor(n, 2, result, path); 9 return result; 10 } 11 12 //Fuction signature 写的好是加分项 13 //此处定义private以及命名为findFactor比直接使用public helper更严谨 14 private void findFactor(int n, int currFactor, List<List<Integer>> result, List<Integer> path) { 15 //base case, find a group of solution 16 if (n == 1 && path.size() > 1) { 17 result.add(new ArrayList(path));//construct new ArrayList for Java 18 return; 19 } 20 for (int i = currFactor; i <= n; i++) { //important to have i <= n for example 4 = 2 * 2 21 if (n % i == 0) { 22 path.add(i); 23 findFactor(n / i, i, result, path); 24 path.remove(path.size() - 1); 25 } 26 } 27 } 28 }
陪老婆准备LinkedIn onsite, 老婆onsite加油!
此题为linkedin常考的一道backtrack 题目
需要注意的细节是
1.只有当中间结果包含至少2个数字时才加入解集
2.循环终止条件为i <= n不然会漏掉最后一个factor
原文:http://www.cnblogs.com/ilovenaomi/p/4884153.html