美文网首页
254. Factor Combinations

254. Factor Combinations

作者: Super_Alan | 来源:发表于2018-04-21 12:20 被阅读0次

    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()

    相关文章

      网友评论

          本文标题:254. Factor Combinations

          本文链接:https://www.haomeiwen.com/subject/pqcxlftx.html