254. 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: 

  1. You may assume that n is always positive.
  2. 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]
]
本题问的是有多少个答案的时候,凡是求一个问题的所有解或者任何一个解的时候,用的都是回溯法。本题的限界条件是被除数处以除数的余数为0,代码如下:
 1 public class Solution {
 2     public List<List<Integer>> getFactors(int n) {
 3         List<List<Integer>> res = new ArrayList<>();
 4         if(n==1) return res;
 5         backtracking(res,new ArrayList<Integer>(),n,2,n);
 6         return res;
 7     }
 8     public void backtracking(List<List<Integer>> res,List<Integer> list,int n,int cur,int target){
 9         if(n==1) res.add(new ArrayList<Integer>(list));
10         else{
11             for(int i=cur;i<=target/2;i++){
12                 if(n%i!=0) continue;
13                 list.add(i);
14                 backtracking(res,list,n/i,i,target);
15                 list.remove(list.size()-1);
16             }
17         }
18     }
19 }

看了discussion的讨论,发现它的解法相对来说比较好,因为他的控制条件是list.size()>1,这样可以确定不是只有它本身了,代码如下:

 1 public List<List<Integer>> getFactors(int n) {
 2     List<List<Integer>> result = new ArrayList<List<Integer>>();
 3     helper(result, new ArrayList<Integer>(), n, 2);
 4     return result;
 5 }
 6 
 7 public void helper(List<List<Integer>> result, List<Integer> item, int n, int start){
 8     if (n <= 1) {
 9         if (item.size() > 1) {
10             result.add(new ArrayList<Integer>(item));
11         }
12         return;
13     }
14     
15     for (int i = start; i <= n; ++i) {
16         if (n % i == 0) {
17             item.add(i);
18             helper(result, item, n/i, i);
19             item.remove(item.size()-1);
20         }
21     }
22 }

 

posted @ 2017-02-13 14:13  CodesKiller  阅读(110)  评论(0编辑  收藏  举报