Factor Combinations Problem
Description
LeetCode Problem 254.
Numbers can be regarded as the product of their factors.
- For example,
8 = 2 x 2 x 2 = 2 x 4.
Given an integer n, return all possible combinations of its factors. You may return the answer in any order.
Note that the factors should be in the range [2, n - 1].
Example 1:
Input: n = 1
Output: []
Example 2:
Input: n = 12
Output: [[2,6],[3,4],[2,2,3]]
Example 3:
Input: n = 37
Output: []
Constraints:
1 <= n <= 10^7
Solution
Approach: Backtracking with Non-Decreasing Factors
The same factors in a different order are the same combination (2 x 6 and 6 x 2), so we only build combinations whose factors are in non-decreasing order. Then each combination is built exactly once.
A recursive search(rest, smallest) keeps the factors chosen so far in a list. rest is what is left to split, and every new factor must be at least smallest:
- If something has been chosen already, then
chosen + [rest]is a valid combination:restitself is the last factor, and it is at least as large as the chosen ones. Record it. - Then try each factor
ffromsmallestwhilef * f <= rest. Iffdividesrest, choosef, callsearch(rest / f, f), and undo the choice.
The limit f * f <= rest keeps the last factor rest / f at least f, so the order stays non-decreasing. It also makes the loop short: we never try factors above the square root.
Nothing is recorded at the top level (with nothing chosen), so n alone is never an answer, and a prime n (or n = 1) gives an empty list.
Complexity: there is one call per combination found (plus the first one), and each call tries factors up to the square root of its rest, so the time is about O(C · √n) for C combinations. The recursion is at most log2 n deep, since every factor is at least 2.
class Solution:
def getFactors(self, n: int) -> List[List[int]]:
answer = []
chosen = [] # factors picked so far, in non-decreasing order
def search(rest, smallest):
"""Split rest into factors that are all >= smallest."""
if chosen:
answer.append(chosen + [rest]) # rest itself is the last factor
f = smallest
while f * f <= rest: # f <= rest / f keeps the last factor >= f
if rest % f == 0:
chosen.append(f)
search(rest // f, f)
chosen.pop()
f += 1
search(n, 2)
return answer