File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments