赞
踩
我正在尝试在leetcode https://leetcode.com/problems/factor-combinations/description/上解决此问题
Numbers can be regarded as product of its factors. For example
8 = 2 x 2 x 2; = 2 x 4.
编写一个接受整数n并返回其因子所有可能组合的函数.
虽然我可以使用dfs方法编写代码,但在输入方面,我仍然很难推动其最坏情况下的时间复杂性.谁能帮忙吗?
public List> getFactors(int n) {
List> result = new ArrayList>();
List current = new ArrayList();
getFactorsHelper(n,2,current,result);
return result;
}
public void getFactorsHelper(int n,int start,List current, List> 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);
}
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。