Print all unique combination of factors of a given number

打印一个数的所有乘数组合,从大到小,不能有重复。

Print all unique combinations of factors of a positive integer.

For example, if the given number is 24 then the output should be:

12*2
8*3
6*4
6*2*2
4*3*2
3*2*2*2

 

public List<String> getFactorNumberCombinations(int n) {
    List<String> result = new ArrayList<String>();
    generateFactors(n, "", n, result);
    return result;
}
    
private void generateFactors(int number, String factors, int prevFactor, List<String> result) {
	for (int i = number / 2; i >= 2; i--) {
		if (number % i == 0 && i <= prevFactor) {
			if (number / i <= i) {
				String entry = factors + i + "*" + number / i;
				result.add(entry);
			}
			generateFactors(number / i, factors + i + "*", i, result);
		}
	}
}

 

重构下代码:

public List<List<Integer>> factorCombinations(int n) {
    List<List<Integer>> res = new ArrayList<>();
    helper(res, n, n / 2, new ArrayList<Integer>());
    return res;
}

private void helper(List<List<Integer>> res, int num, int largestFactor,
        List<Integer> path) {
    if (num == 1) {
        res.add(new ArrayList<Integer>(path));
        return;
    }
    for (int i = largestFactor; i > 1; i--) {
        if (num % i == 0) {
            path.add(i);
            helper(res, num / i, i, path);
            path.remove(path.size() - 1);
        }
    }
}

 

参考:

http://www.shuatiblog.com/blog/2015/02/13/combination-of-factors/

你可能感兴趣的:(recursive,number factors)