[LinkedIn]Combination factors

From Here

Linkedin 的一道题目

Keep track of the current remain factor to be decomposed, LargestFactor is the largest possible factor to decompose (so that we don’t need to try anything larger than that).

For each level we try to decompose the current remaining factor.

import java.util.*;
public class Test {
    public List<List<Integer>> factorCombinations(int n) {
        List<List<Integer>> ans = new ArrayList<List<Integer>>();
        helper(ans, n, n/2, new ArrayList<Integer>());
        return ans;
    }
    private void helper(List<List<Integer>> ans, int num, int largestFactor, List<Integer> path) {
        if (num == 1) {
            ans.add(new ArrayList<Integer>(path));
            return;
        }
        for (int i = largestFactor; i > 1; i--) {
            if (num % i == 0) {
                path.add(i);
                helper(ans, num / i, i, path);
                path.remove(path.size() - 1);
            }
        }
    }
    public static void main(String[] args) {
        Test t = new Test();
        List<List<Integer>> l = t.factorCombinations(24);
        for (List<Integer> li : l) {
            for (Integer i : li) {
                System.out.print(i+" ");
            }
            System.out.println();
        }
    }
}
posted on 2015-03-31 11:32  Seth_L  阅读(158)  评论(0编辑  收藏  举报