Skip to content

Commit dd511fd

Browse files
committed
Complete Leetcode 254
1 parent 2372c43 commit dd511fd

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Factor Combinations
2+
3+
Problem can be found in [here](https://leetcode.com/problems/factor-combinations/)!
4+
5+
### [Solution](/Backtracking/254-FactorCombinations/solution.py): Backtracking
6+
7+
```python
8+
def getFactors(n: int) -> List[List[int]]:
9+
def helper(factors: List[int], least_factor: int, target: int):
10+
if len(factors) > 0:
11+
result.append(factors + [target])
12+
for candidate_factor in range(least_factor, int(sqrt(target))+1):
13+
if target % candidate_factor == 0:
14+
helper(factors+[candidate_factor], candidate_factor, target // candidate_factor)
15+
16+
result = []
17+
if n == 1:
18+
return result
19+
helper([], 2, n)
20+
return result
21+
```
22+
23+
Explanation: We can use the backtracking technique to solve this problem. We will append valid factor into the factors list ascendingly to avoid duplicated factor combinations. If n = 12, we will only append [2, 2, 3] but not [2, 3, 2] with the help of a variable called least_factor.
24+
25+
Time Complexity: ![O(logn*logn)](<https://latex.codecogs.com/svg.image?\inline&space;O(logn*logn)>), Space Complexity: ![O(n)](<https://latex.codecogs.com/svg.image?\inline&space;O(n)>)
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
from math import sqrt
2+
from typing import List
3+
4+
5+
class Solution:
6+
def getFactors(self, n: int) -> List[List[int]]:
7+
def helper(factors: List[int], least_factor: int, target: int):
8+
if len(factors) > 0:
9+
result.append(factors + [target])
10+
for candidate_factor in range(least_factor, int(sqrt(target))+1):
11+
if target % candidate_factor == 0:
12+
helper(factors+[candidate_factor], candidate_factor, target // candidate_factor)
13+
14+
result = []
15+
if n == 1:
16+
return result
17+
helper([], 2, n)
18+
return result

0 commit comments

Comments
 (0)