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 integernand 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]
]

思路

  • target n 从 2 ~ n开始尝试除法
  • tricky的地方:
    • i <= n
    • exit处需要判断path的size
    public List<List<Integer>> getFactors(int n) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> path = new ArrayList<Integer>();
        if (n < 2) return res;

        helper(res, path, n, 2);
        return res;
    }

    private void helper(List<List<Integer>> res, List<Integer> path, int n, int start) {
        if (n <= 1) {
            if (path.size() > 1)
                res.add(new ArrayList<Integer>(path));
            return;
        }


        for (int i = start; i <= n; i++) {
            if (n % i != 0) continue;
            path.add(i);
            helper(res, path, n / i, i);
            path.remove(path.size() - 1);
        }
    }

results matching ""

    No results matching ""