254. Factor Combinations

Problem:
Numbers can be regarded as product of its factors. For example,
8 = 2 x 2 x 2;
  = 2 x 4.
Write a function that takes an integer n and return all possible combinations of its factors.
Note: 
  1. You may assume that n is always positive.
  2. Factors should be greater than 1 and less than n.
Examples: 
input: 1
output: 
[]
input: 37
output: 
[]
input: 12
output:
[
  [2, 6],
  [2, 2, 3],
  [3, 4]
]
input: 32
output:
[
  [2, 16],
  [2, 2, 8],
  [2, 2, 2, 4],
  [2, 2, 2, 2, 2],
  [2, 4, 4],
  [4, 8]
]
Analysis:
Similar to combinations. The tricky part is i's upper bound should include remain, and check size of list to decide whether to add this list.

Solution:

class Solution {
    public List<List<Integer>> getFactors(int n) {
        List<List<Integer>> res = new ArrayList<>();
        dfs(res, new ArrayList<>(), n, 2);
        return res;
    }

    private void dfs(List<List<Integer>> res, List<Integer> list, int remain, int start) {
        if (remain == 1 && list.size() > 1) {
            res.add(new ArrayList<>(list));
        }

        for (int i = start; i <= remain; i++) {
            if (remain % i == 0) {
                list.add(i);
                dfs(res, list, remain / i, i);
                list.remove(list.size() - 1);
            }
        }
    }
}

评论

此博客中的热门博文

776. Split BST

663. Equal Tree Partition

532. K-diff Pairs in an Array