Factor Combinations

来源:互联网 发布:中学生编程竞赛 编辑:程序博客网 时间:2024/04/17 05:29

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]]

这题backtracking的妙处在于:把上限进行改变,这样可以减少很多计算。上限n进行改变。最后需要注意的是,list.size() > 1的作用是把n本身去掉。

比如:n = 12, 结果会包括12本身,它只有一个,是不成立的。这题必须得<=n,因为我是变上限,来求质因子,所以必须等于n才能整除。最后再用list.size() >1来去除本身。

public class Solution {    public List<List<Integer>> getFactors(int n) {        List<List<Integer>> lists = new ArrayList<List<Integer>>();        if(n<=2) return lists;        ArrayList<Integer> list = new ArrayList<Integer>();        collect(lists, n, 2, list);        return lists;    }        public void collect(List<List<Integer>> lists, int n, int start, List<Integer> list) {        if(n == 1) {            if(list.size() >1){                lists.add(new ArrayList<Integer>(list));            }            return;        }        for(int i=start; i<=n; i++){            if(n % i == 0){                list.add(i);                collect(lists, n/i, i, list);                list.remove(list.size()-1);            }        }    }}


0 0
原创粉丝点击