https://leetcode.com/problems/factor-combinations/description/
很经典的 Backtracking 问题,尝试所有可能。题解如下:
class Solution {
public List<List<Integer>> getFactors(int n) {
LinkedList<List<Integer>> res = new LinkedList<>();
if (n <= 3) {
return res;
}
LinkedList<Integer> path = new LinkedList<>();
backtracking(2, n, path, res);
res.removeLast(); // remove last list with only n
return res;
}
private void backtracking(int start, int target, LinkedList<Integer> path, List<List<Integer>> res) {
if (target == 1) {
List<Integer> list = new LinkedList<>(path);
res.add(list);
return;
}
for (int i = start; i <= target; i++) {
if (target % i == 0) {
path.add(i);
backtracking(i, target / i, path, res);
path.removeLast();
}
}
}
}
应该是可以是用 Memory 做优化的,有蛮多重复计算。貌似优化并不容易实现,因为涉及到起始计算位置。
LinkedList class in Java: removeLast()
网友评论