Factor Combinations(Medium)因式分解

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. Each combination's factors must be sorted ascending, for example: The factors of 2 and 6 is [2, 6], not [6, 2].
  2. You may assume that n is always positive.
  3. Factors should be greater than 1 and less than n.

例子:

input: 1
output: 
[]

input: 12
output:
[
  [2, 6],
  [2, 2, 3],
  [3, 4]
]


input: 37
output: 
[]


input: 32
output:
[
  [2, 16],
  [2, 2, 8],
  [2, 2, 2, 4],
  [2, 2, 2, 2, 2],
  [2, 4, 4],
  [4, 8]
]

解法:打印一个数的所有乘数组合,从小到大,不要有重复

public List<List<Integer>> getFactorsS(int n) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if (n <= 2) {
            return res;
        }
        List<Integer> tem = new ArrayList<Integer>();
        helperS(res, tem, n, 2);
        return res;
}

public void helperS(List<List<Integer>> res, List<Integer> tem, int target,int div) {
        if (target <= 1) {
            if (tem.size() > 1) {
                res.add(new ArrayList<Integer>(tem));
            }
            return;
        }

        for (int i = div; i <= target; i++) {
            if (target % i == 0) {
                tem.add(i);
                helperS(res, tem, target / i, i);
                tem.remove(tem.size() - 1);
            }

        }
}

解法:打印一个数的所有乘数组合,从大到小,不要有重复

 public List<List<Integer>> getFactors(int n) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if (n <= 1) {
            return result;
        }

        List<Integer> curr = new ArrayList<>();
        helper(result, n, n / 2, curr);
        return result;
    }

    private void helper(List<List<Integer>> result, int target, int div,
                        List<Integer> curr) {
        if (target == 1) {
            result.add(new ArrayList<Integer>(curr));
            return;
        }

        for (int i = div; i > 1; i--) {
            if (target % i == 0) {
                curr.add(i);
                helper(result, target / i, i, curr);
                curr.remove(curr.size() - 1);
            }
        }
    }

results matching ""

    No results matching ""