Skip to content

Commit

Permalink
[DFS] Add a solution to Factor Combinations
Browse files Browse the repository at this point in the history
  • Loading branch information
Yi Gu committed Dec 7, 2016
1 parent a8ba9fc commit a3e0293
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions DFS/FactorCombinations.swift
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()
}
}
}
}

0 comments on commit a3e0293

Please sign in to comment.