码迷,mamicode.com
首页 > 其他好文 > 详细

254. Factor Combinations

时间:2015-12-03 02:05:09      阅读:710      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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. Each combination‘s factors must be sorted ascending, for example: The factors of 2 and 6 is [2, 6], not [6, 2].
  2. You may assume that n is always positive.
  3. 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]
]

链接: http://leetcode.com/problems/factor-combinations/

题解:

求一个数的所有factor,这里我们又想到了DFS + Backtracking, 需要注意的是,factor都是>= 2的,并且在此题里,这个数本身不能算作factor,所以我们有了当n <= 1时的判断 if(list.size() > 1) add the result to res.

Time Complexity - O(2n), Space Complexity - O(n).

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

 

Reference:

 

254. Factor Combinations

标签:

原文地址:http://www.cnblogs.com/yrbbest/p/5014873.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!