[LinkedIn]Combination factors

来源:互联网 发布:糖糖淘宝客怎么样 编辑:程序博客网 时间:2024/05/16 02:04

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>>();        //change largestFactor to n to start from itself        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();        }    }}

a more clear way to do it using , credit to Jiasen Lin~

import java.util.ArrayList;import java.util.List;import java.util.Stack;public class Factors {    public List<List<Integer>> factorCombinations(int n) {        List<List<Integer>> ans = new ArrayList<List<Integer>>();        // change largestFactor to n to start from itself        Stack<Integer> stack = new Stack<Integer>();        helper(ans, n, n, stack);        return ans;    }    private void helper(List<List<Integer>> ans, int num, int largestFactor, Stack<Integer> stack) {        if (num == 1) {            List<Integer> list = new ArrayList<Integer>();            for (int i : stack) {                list.add(i);            }            ans.add(list);            return;        }        for (int i = largestFactor; i > 1; i--) {            if (num % i == 0) {                stack.push(i);                int newNum = num / i;                helper(ans, newNum, Math.min(newNum, i), stack);                stack.pop();            }        }    }    public static void main(String[] args) {        Factors t = new Factors();        List<List<Integer>> l = t.factorCombinations(24);        for (List<Integer> li : l) {            for (Integer i : li) {                System.out.print(i + " ");            }            System.out.println();        }    }}
0 0
原创粉丝点击