diff --git a/src/0241.Different-Ways-to-Add-Parentheses/Solution.go b/src/0241.Different-Ways-to-Add-Parentheses/Solution.go index 6a10aa77e..cfc60fd35 100644 --- a/src/0241.Different-Ways-to-Add-Parentheses/Solution.go +++ b/src/0241.Different-Ways-to-Add-Parentheses/Solution.go @@ -1,5 +1,55 @@ package Solution +import "strconv" + func diffWaysToCompute(input string) []int { - return []int{} + return ways(input, map[string][]int{}) +} + +func calculate(a, b int, operate rune) int { + switch operate { + case '+': + return a + b + case '-': + return a - b + case '*': + return a * b + default: + panic("operate not exist") + } +} + +func ways(input string, cache map[string][]int) []int { + if _, ok := cache[input]; ok { + return cache[input] + } + + ans := []int{} + + for i := 0; i < len(input); i++ { + ch := input[i] + + if ch == '+' || ch == '-' || ch == '*' { + left := input[:i] + right := input[i+1:] + + l := ways(left, cache) + r := ways(right, cache) + + for _, a := range l { + for _, b := range r { + ans = append(ans, calculate(a, b, rune(ch))) + } + } + } + } + + if len(ans) == 0 { + number, _ := strconv.Atoi(input) + ans = append(ans, number) + } + + cache[input] = ans + + return ans } diff --git a/src/0241.Different-Ways-to-Add-Parentheses/Solution_test.go b/src/0241.Different-Ways-to-Add-Parentheses/Solution_test.go index 673e32c5f..5cc26ff2a 100644 --- a/src/0241.Different-Ways-to-Add-Parentheses/Solution_test.go +++ b/src/0241.Different-Ways-to-Add-Parentheses/Solution_test.go @@ -1,7 +1,6 @@ package Solution import ( - "reflect" "strconv" "testing" ) @@ -21,9 +20,17 @@ func TestSolution(t *testing.T) { for i, c := range cases { t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) { got := diffWaysToCompute(c.inputs) - if !reflect.DeepEqual(got, c.expect) { - t.Fatalf("expected: %v, but got: %v, with inputs: %v", - c.expect, got, c.inputs) + if len(got) != len(c.expect) { + t.Fatalf("expected: %v, but got: %v, with inputs: %v", c.expect, got, c.inputs) + } + m := make(map[int]int) + for v := range got { + m[v]++ + } + for v := range c.expect { + if _, ok := m[v]; !ok { + t.Fatalf("expected: %v, but got: %v, with inputs: %v", c.expect, got, c.inputs) + } } }) } diff --git a/src/0621.Task-Scheduler/Solution.go b/src/0621.Task-Scheduler/Solution.go index 70f46222c..2e4f21583 100644 --- a/src/0621.Task-Scheduler/Solution.go +++ b/src/0621.Task-Scheduler/Solution.go @@ -1,8 +1,31 @@ package Solution +import "sort" - +func max(a, b int) int { + if a > b { + return a + } + return b +} func leastInterval(tasks []byte, n int) int { - return 0 + tmp := make([]int, 26) + temp := []int{} + p := 1 + for _, v := range tasks { + tmp[v-'A']++ + } + for _, v := range tmp { + temp = append(temp, v) + } + sort.Slice(temp, func(a, b int) bool { + return temp[a] > temp[b] + }) + for i := 1; i < len(temp); i++ { + if temp[0] == temp[i] { + p++ + } + } + return max((n+1)*(temp[0]-1)+p, len(tasks)) }