forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[DFS] Add a solution to Factor Combinations
- Loading branch information
Yi Gu
committed
Dec 7, 2016
1 parent
a8ba9fc
commit a3e0293
Showing
1 changed file
with
39 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
/** | ||
* Question Link: https://leetcode.com/problems/factor-combinations/ | ||
* Primary idea: Classic Depth-first Search | ||
* | ||
* Time Complexity: O(n^n), Space Complexity: O(2^n - 1) | ||
* | ||
*/ | ||
|
||
class FactorCombinations { | ||
func getFactors(_ n: Int) -> [[Int]] { | ||
var res = [[Int]]() | ||
var path = [Int]() | ||
|
||
dfs(&res, &path, n, 2) | ||
|
||
return res | ||
} | ||
|
||
private func dfs(_ res: inout [[Int]], _ path: inout [Int], _ n: Int, _ start: Int) { | ||
if n == 1 { | ||
if path.count > 1 { | ||
res.append(Array(path)) | ||
} | ||
return | ||
} | ||
|
||
if start > n { | ||
return | ||
} | ||
|
||
for i in start ... n { | ||
if n % i == 0 { | ||
path.append(i) | ||
dfs(&res, &path, n / i, i) | ||
path.removeLast() | ||
} | ||
} | ||
} | ||
} |