Skip to content

Commit ba01b65

Browse files
author
Yi Gu
committed
[DP] Add a solution to Different Ways to Add Parentheses
1 parent 830496e commit ba01b65

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/different-ways-to-add-parentheses/
3+
* Primary idea: Divide and Conquer, calculate left and right separately and union results
4+
*
5+
* Note: Keep a memo dictionary to avoid duplicate calculations
6+
* Time Complexity: O(n^n), Space Complexity: O(n)
7+
*
8+
*/
9+
10+
class DifferentWaysAddParentheses {
11+
var memo = [String: [Int]]()
12+
13+
func diffWaysToCompute(_ input: String) -> [Int] {
14+
if let nums = memo[input] {
15+
return nums
16+
}
17+
18+
var res = [Int]()
19+
let chars = Array(input.characters)
20+
21+
for (i, char) in chars.enumerated() {
22+
if char == "+" || char == "*" || char == "-" {
23+
let leftResults = diffWaysToCompute(String(chars[0 ..< i]))
24+
let rightResults = diffWaysToCompute(String(chars[i + 1 ..< chars.count]))
25+
26+
for leftRes in leftResults {
27+
for rightRes in rightResults {
28+
if char == "+" {
29+
res.append(leftRes + rightRes)
30+
}
31+
if char == "-" {
32+
res.append(leftRes - rightRes)
33+
}
34+
if char == "*" {
35+
res.append(leftRes * rightRes)
36+
}
37+
}
38+
}
39+
}
40+
}
41+
42+
if res.count == 0 {
43+
res.append(Int(input)!)
44+
}
45+
46+
memo[input] = res
47+
48+
return res
49+
}
50+
}

0 commit comments

Comments
 (0)