Skip to content

Commit

Permalink
Merge pull request soapyigu#197 from soapyigu/DP
Browse files Browse the repository at this point in the history
[DP] Add a solution to Different Ways to Add Parentheses
  • Loading branch information
soapyigu authored Jan 6, 2017
2 parents 16f24a4 + ba01b65 commit 1860d76
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions DP/DifferentWaysAddParentheses.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/**
* Question Link: https://leetcode.com/problems/different-ways-to-add-parentheses/
* Primary idea: Divide and Conquer, calculate left and right separately and union results
*
* Note: Keep a memo dictionary to avoid duplicate calculations
* Time Complexity: O(n^n), Space Complexity: O(n)
*
*/

class DifferentWaysAddParentheses {
var memo = [String: [Int]]()

func diffWaysToCompute(_ input: String) -> [Int] {
if let nums = memo[input] {
return nums
}

var res = [Int]()
let chars = Array(input.characters)

for (i, char) in chars.enumerated() {
if char == "+" || char == "*" || char == "-" {
let leftResults = diffWaysToCompute(String(chars[0 ..< i]))
let rightResults = diffWaysToCompute(String(chars[i + 1 ..< chars.count]))

for leftRes in leftResults {
for rightRes in rightResults {
if char == "+" {
res.append(leftRes + rightRes)
}
if char == "-" {
res.append(leftRes - rightRes)
}
if char == "*" {
res.append(leftRes * rightRes)
}
}
}
}
}

if res.count == 0 {
res.append(Int(input)!)
}

memo[input] = res

return res
}
}

0 comments on commit 1860d76

Please sign in to comment.