Skip to content

Commit 60cf4cc

Browse files
committed
different_ways_to_add_parentheses
1 parent 469d86c commit 60cf4cc

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t
196196
#### [238. product of array except self](https://github.com/hitzzc/go-leetcode/tree/master/product_of_array_except_self)
197197
#### [239. Sliding Window Maximum](https://github.com/hitzzc/go-leetcode/tree/master/sliding_window_maximum)
198198
#### [240. Search a 2D Matrix II](https://github.com/hitzzc/go-leetcode/tree/master/search_a_2D_matrix_II)
199+
#### [241. Different Ways to Add Parentheses](https://github.com/hitzzc/go-leetcode/tree/master/different_ways_to_add_parentheses)
199200

200201

201202

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package different_ways_to_add_parentheses
2+
3+
import (
4+
"strconv"
5+
)
6+
7+
func diffWaysToCompute(input string) []int {
8+
return helper(input, map[string][]int{})
9+
}
10+
11+
func helper(input string, cache map[string][]int) []int {
12+
if v, ok := cache[input]; ok {
13+
return v
14+
}
15+
ret := []int{}
16+
for i := range input {
17+
if input[i] == '+' || input[i] == '-' || input[i] == '*' {
18+
left := helper(input[:i], cache)
19+
right := helper(input[i+1:], cache)
20+
for j := range left {
21+
for k := range right {
22+
switch input[i] {
23+
case '+':
24+
ret = append(ret, left[j]+right[k])
25+
case '-':
26+
ret = append(ret, left[j]-right[k])
27+
case '*':
28+
ret = append(ret, left[j]*right[k])
29+
}
30+
}
31+
}
32+
}
33+
}
34+
if len(ret) == 0 {
35+
num, _ := strconv.Atoi(input)
36+
ret = append(ret, num)
37+
}
38+
cache[input] = ret
39+
return ret
40+
}

0 commit comments

Comments
 (0)