您的位置:首页 > 其它

Leetcode: Factor Combinations

2015-12-23 02:33 225 查看
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:
Each combination's factors must be sorted ascending, for example: The factors of 2 and 6 is [2, 6], not [6, 2].
You may assume that n is always positive.
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]
]


这题就是不停的DFS, 直到 n == 1. 有个判断条件 if (item.size() > 1) 是为了防止答案是自己本身n, 按照题意, 这是不允许的.

参考了:http://www.meetqun.com/thread-10673-1-1.html

时间复杂度, 个人觉得是O(n*log(n)), 一开始觉得是O(n!), 但後来想想好像没那麽大. 我的想法是,
最一开始的for回圈是n, 但是一旦进入了下一个DFS, 每次最差都是 n / i在减小, 这边就是log(n), 所以总共是O(n*log(n)), 有错还请指正.

public class Solution {
public List<List<Integer>> getFactors(int n) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> item = new ArrayList<Integer>();
if (n <= 3) return res;
helper(2, n, res, item);
return res;
}

public void helper(int start, int n, List<List<Integer>> res, List<Integer> item) {
if (n == 1) {
if (item.size() > 1) {
res.add(new ArrayList<Integer>(item));
return;
}
}
for (int i=start; i<=n; i++) {
if (n%i == 0) {
item.add(i);
helper(i, n/i, res, item);
item.remove(item.size()-1);
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: