方法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);
}
}
}
具体优化的分析如下:
总结:
- 无