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.
class Solution {
    public List<List<Integer>> getFactors(int n) {
        List<List<Integer>> res = new ArrayList<>();
        if(n <= 1)
            return res;

        List<Integer> line = new ArrayList<>();
        helper(res, line, 2, n);

        res.remove(res.size() - 1);

        return res;
    }

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

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

results matching ""

    No results matching ""