Factor Combinations
Question (LC.254)
Find all possible factor combinations of a number.
Example
I: 8
O: [ [2,2,2], [2,4] ]
I: 1
O: []
I: 2
O: []
I: 9
O: [ [3,3] ]Assume n > 0. How large can n get? n cannot be very large. what about 1? 1x1x1... Assume factors greater than 1.
Attempt #1
1. Define subproblem
factorSearch(result, factors, dividend) =>
add all factor combinations of dividend to result (with given prefix factors)
2. Recursive calls
for factor from 2 to dividend / 2
if (divident % factor != 0) continue
factorSearch(result, factors.add(factor), divident / factor)
3. Bases cases
if (dividend == 1)
result.add(new List(factors))What's wrong with this approach?
We need to choose representative for each combination. Sorted is the easiest to work with. We want to put in the smallest factor as much as possible before we move on to a larger factor.
Corrected Code
Time & Space Complexity
Time O(n*2^n) Space O(n)
Last updated