原题链接在这里:https://leetcode.com/problems/factor-combinations/
题目:
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
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] ]
题解:
和Combination Sum 都是backtracking 的题目. factor 从2 开始,若是target能除以factor,就把factor加到item中,继续用target/factor做新的target找. Base case 是target变成了1, 并且item的size要大于1. 这里对item 的size 有要求是因为若初始target = 2, 返回结果是不应该包含{2}这个item的。
Time Complexity: Exponential. Space: log(target).
AC Java:
1 public class Solution { 2 public List<List<Integer>> getFactors(int n) { 3 List<List<Integer>> res = new ArrayList<List<Integer>>(); 4 if(n<=1){ 5 return res; 6 } 7 8 findFactors(n, 2, new ArrayList<Integer>(), res); 9 return res; 10 } 11 12 //注意要写好的signature 13 private void findFactors(int n, int factor, List<Integer> item, List<List<Integer>> res){ 14 //base case 不但要n==1, 还需要item.size() > 1, 否则n = 2, 就会添加一个item {2}. 15 if(n == 1 && item.size() > 1){ 16 res.add(new ArrayList<Integer>(item)); 17 return; 18 } 19 for(int i = factor; i<=n; i++){ 20 if(n%i == 0){ 21 item.add(i); 22 findFactors(n/i, i, item, res); 23 item.remove(item.size()-1); 24 } 25 } 26 } 27 }