Factor Combinations — LeetCode 254 Python Solution
MediumLeetCode PremiumBacktracking
- Problem
- #254
- Pattern
- Backtracking
- Reading time
- 3 min
- Source
- leetcode.com
The problem
Numbers can be regarded as the product of their factors. For example, 8 = 2 x 2 x 2 = 2 x 4.
Example
- Input
- n = 1
- Output
- []
Python solution
Python
class Solution:
def getFactors(self, n: int) -> List[List[int]]:
def dfs(n, i):
if t:
ans.append(t + [n])
j = i
while j * j <= n:
if n % j == 0:
t.append(j)
dfs(n // j, j)
t.pop()
j += 1
t = []
ans = []
dfs(n, 2)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | Exponential (worst case) |
| Space | O(depth) auxiliary |
Pattern: Backtracking
Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 254. Factor Combinations is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Backtracking.
The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 254. Factor Combinations?
- LeetCode 254. Factor Combinations is rated Medium on LeetCode.
- What topics does LeetCode 254. Factor Combinations cover?
- LeetCode 254. Factor Combinations is tagged Backtracking on LeetCode.
- Is LeetCode 254. Factor Combinations a premium problem?
- Yes. LeetCode 254. Factor Combinations is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.