254. Factor Combinations

https://leetcode.com/problems/factor-combinations/description/

很经典的 Backtracking 问题,尝试所有可能。题解如下:

class Solution {
    public List> getFactors(int n) {
        LinkedList> res = new LinkedList<>();
        
        if (n <= 3) {
            return res;
        }
        
        LinkedList 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 path, List> res) {
        if (target == 1) {
            List 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()

你可能感兴趣的:(254. Factor Combinations)