【发布时间】:2018-01-21 14:19:21
【问题描述】:
我正在尝试在 leetcode https://leetcode.com/problems/factor-combinations/description/ 上解决这个问题
数字可以看作是其因子的乘积。例如
8 = 2 x 2 x 2; = 2 x 4。
编写一个接受整数 n 并返回其因子的所有可能组合的函数。
虽然我能够使用 dfs 方法编写代码,但我很难在输入方面驱动其最坏情况的时间复杂度。有人可以帮忙吗?
public List<List<Integer>> getFactors(int n) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<Integer> current = new ArrayList<Integer>();
getFactorsHelper(n,2,current,result);
return result;
}
public void getFactorsHelper(int n,int start,List<Integer> current, List<List<Integer>> result){
if(n<=1 && current.size()>1){
result.add(new ArrayList<>(current));
return;
}
for(int i=start;i<=n;i++){
if(n%i==0) {
current.add(i);
getFactorsHelper(n/i,i,current,result);
current.remove(current.size()-1);
}
}
}
【问题讨论】:
-
相对于什么变量的时间复杂度?
-
关于输入 n
-
好的,但请记住,它会有很大的波动 - 例如 127 只有一个输出,而 128 有负载。
-
是的。我对最坏情况的复杂性感兴趣。
-
这里的“最坏情况”是什么意思? (我并不是想变得困难,我想指出您的问题可能没有意义,因为它目前提出。)
标签: java algorithm recursion time-complexity depth-first-search