Topic:
Numbers can 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:
- Each combination ' s factors must are sorted ascending, for example:the factors of 2 and 6
[2, 6]
are, not [6, 2]
.
- You are assume that n are always positive.
- Factors should is greater than 1 and less than n.
Examples:
Input1
Output
[]
Input
37
Output
[]
Input
12
Output
[ [2, 6], [2, 2, 3], [3, 4]]
Input
32
Output
[ 2, +], [2, 2, 8], [ 2, 2, 2, 4], [2, 2, 2, 2, 2], [2, 4, 4], [4 , 8]]
Links: http://leetcode.com/problems/factor-combinations/
Exercises
Ask for a number of all factor, here we think of the DFS + backtracking, it should be noted that factor are >= 2, and in this problem, the number itself can not be counted as factor, so we have when n <= 1 o'clock judgment if ( List.size () > 1) Add the result to Res.
Time Complexity-o (2n), Space complexity-o (n).
Public classSolution { PublicList<list<integer>> Getfactors (intN) {List<List<Integer>> res =NewArraylist<>(); List<Integer> list =NewArraylist<>(); Getfactors (res, list, N,2); returnRes; } Private voidGetfactors (list<list<integer>> res, list<integer> List,intNintfactor) { if(N <= 1) { if(List.size () > 1) Res.add (NewArraylist<integer>(list)); return; } for(inti = factor; I <= N; i++) { if(n% i = = 0) {list.add (i); Getfactors (res, list, n/I, i); List.remove (List.size ()-1); } } }}
Reference:
254. Factor Combinations