
方法1: 这题其实和39题差不多,39是sum,这题是乘积。时间复杂O(n^logn),空间复杂logn。时间复杂度分析如下:

class Solution {
public List<List<Integer>> getFactors(int n) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
dfs(n, 2, path, res);
return res;
}
public void dfs(int n, int start, List<Integer> path, List<List<Integer>> res){
if(n == 1) {
if(path.size() > 1) res.add(new ArrayList<>(path));
return;
}
for(int i = start; i <= n; i++){
if(n % i != 0) continue;
path.add(i);
dfs(n/i, i, path, res);
path.remove(path.size()-1);
}
}
}
方法2: 方法1的小优化。时间复杂度变为O(sqrt(n)^logn)。
class Solution {
public List<List<Integer>> getFactors(int n) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
dfs(n, 2, path, res);
return res;
}
public void dfs(int n, int start, List<Integer> path, List<List<Integer>> res){
for(int i = start; i * i<= n; i++){
if(n % i != 0) continue;
path.add(i);
path.add(n / i);
res.add(new ArrayList<>(path));
path.remove(path.size()-1);
dfs(n/i, i, path, res);
path.remove(path.size()-1);
}
}
}
具体优化的分析如下:
总结:
- 无
这篇博客探讨了两种方法来找到一个整数的所有因子,方法1基于回溯,时间复杂度为O(n^logn),而方法2通过优化将时间复杂度降低到O(sqrt(n)^logn)。博主详细分析了算法的实现和优化过程。
1468

被折叠的 条评论
为什么被折叠?



