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:
- You are assume that n are always positive.
- Factors should is greater than 1 and less than n.
Examples:
Input1
Output
[]
Input37
Output
[]
Input12
Output
[ [2, 6], [2, 2, 3], [3, 4]]
Input32
Output
[ 2, +], [2, 2, 8], [ 2, 2, 2, 4], [2, 2, 2, 2, 2], [2, 4, 4], [4 , 8]]
This topic needs to be noted is how to avoid duplication, need to add a sentinel in the backtracking inputs, in the backtracking cycle from Sentinel start.
Publicilist<ilist<int>> Getfactors (intN) {varres =Newlist<ilist<int>>(); if(n = =0)returnRes; Backtracking (n,Newlist<int> (), Res,2); returnRes; } Private voidBacktracking (intN, list<int> cur, ilist<ilist<int>> Res,intLast ) { if(n==1) { if(cur. Count () >1) Res. ADD (Newlist<int>(cur)); } Else { for(inti = last;i<= n;i++) { if(n%i = =0) {cur. ADD (i); Backtracking (n/i,cur,res,i); Cur. RemoveAt (cur. Count ()-1); } } } }
The above algorithm can be optimized because the smaller multiplier does not exceed the square root of the original number when an integer is divided into two integer multiples. You can limit the upper bound of the loop to sqrt (n).
Publicilist<ilist<int>> Getfactors (intN) {varres =Newlist<ilist<int>>(); if(n = =0)returnRes; Backtracking (n,Newlist<int> (), Res,2); returnRes; } Private voidBacktracking (intN, list<int> cur, ilist<ilist<int>> Res,intLast ) { if(cur. Count () >0) {cur. ADD (n); Res. ADD (Newlist<int>(cur)); Cur. RemoveAt (cur. Count ()-1); } for(inti = last;i<= (int) math.sqrt (n); i++) { if(n%i = =0) {cur. ADD (i); Backtracking (n/i,cur,res,i); Cur. RemoveAt (cur. Count ()-1); } } }
254. Factor Combinations