forked from WenchaoD/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.
Merge pull request soapyigu#197 from soapyigu/DP
[DP] Add a solution to Different Ways to Add Parentheses
- Loading branch information
Showing
1 changed file
with
50 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,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 | ||
} | ||
} |