forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 1
/
DifferentWaysAddParentheses.swift
50 lines (42 loc) · 1.53 KB
/
DifferentWaysAddParentheses.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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
}
}