class Solution {
public List<List<Integer>> getFactors(int n) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (n <= 3) return res;
backtrack(n, 2, res, new ArrayList<Integer>());
return res;
}
private void backtrack(int n, int start, List<List<Integer>> res, ArrayList<Integer> list) {
if (n <= 1) {
if (list.size() > 1) res.add(new ArrayList<Integer>(list));
return ;
}
for (int i = start; i <= n; i++) {
if (n % i == 0) {
list.add(i);
backtrack(n / i, i, res, list);
list.remove(list.size() - 1);
}
}
}
}
If we iterate in [2, sqrt(n)] it's even faster:
class Solution {
public List<List<Integer>> getFactors(int n) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (n <= 3) return res;
backtrack(n, 2, res, new ArrayList<Integer>());
return res;
}
private void backtrack(int n, int start, List<List<Integer>> res, ArrayList<Integer> list) {
for (int i = start; i * i <= n; i++) {
if (n % i == 0) {
list.add(i);
list.add(n / i);
res.add(new ArrayList<>(list));
list.remove(list.size() - 1);
backtrack(n / i, i, res, list);
list.remove(list.size() - 1);
}
}
}
}
If we iterate in [2, n]:
If we iterate in [2, sqrt(n)] it's even faster: