step 1: 先按照从大到小的顺序找出所有的因数
step 2: 递归地解决问题(类似于99 cents)
需要注意的是在尝试完本层所有的branch以后退回上一层之前需要状态重置即删除之前加入path的数。
class Solution {
public List<List<Integer>> getFactors(int n) {
List<List<Integer>> res = new ArrayList<>();
// Corner Case
if(n <= 1){
return res;
}
List<Integer> factors = helper(n);
List<Integer> path = new ArrayList<>();
backtrack(n, factors, 0, path, res);
return res;
}
private void backtrack(int n, List<Integer> factors, int idx, List<Integer> path, List<List<Integer>> res){
// Base Case
if(idx == factors.size()){
if(n == 1){
res.add(new ArrayList<>(path));
}
return;
}
backtrack(n, factors, idx + 1, path, res);
int factor = factors.get(idx);
int count = 0;
while(n % factor == 0){
count++;
path.add(factor);
n /= factor;
backtrack(n, factors, idx + 1, path, res);
}
for(; count > 0; count--){
path.remove(path.size() - 1);
}
}
private List<Integer> helper(int n){
List<Integer> factors = new ArrayList<>();
for(int i = n / 2; i > 1; i--){
if(n % i == 0){
factors.add(i);
}
}
return factors;
}
}