[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
- [LinkedIn]Combination factors
- LinkedIn 面试题:字符串的全排列(Permutation)和组合(Combination)
- combination
- combination
- Combination
- My LinkedIN
- From LinkedIn
- linkedin interview
- linkedin oauth
- Prime Factors
- Prime Factors
- Factorial Factors
- Pricing Factors
- PAT1096Consecutive Factors
- Prime Factors
- Prime Factors
- Vector的学习
- 第四周项目二
- 动画相关的工具类AnimationUtil
- 软件产品 软件版本
- Android性能优化 (一)- ListView
- [LinkedIn]Combination factors
- 第四周项目1.1
- 大夏shell编程学习笔记(1)
- zookeeper addauth
- package和import的使用
- GetComponent<T>()详解
- 第四周项目1.2
- iOS最佳实践
- 第四周项目1.3