MediumNo. 0254LeetCode Premium
Factor Combinations — LeetCode 254 Python Solution
- Pattern
- Backtracking
- Topics
- 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
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
- Time
- Exponential (worst case)
- Space · auxiliary
- O(depth)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0257 | Binary Tree Paths | Easy |
| 0039 | Combination Sum | Medium |
| 0040 | Combination Sum II | Medium |
| 0046 | Permutations | Medium |
| 0047 | Permutations II | Medium |
| 0051 | N-Queens | Hard |
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.