-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path306_additive-number_test.go
71 lines (64 loc) · 1.35 KB
/
306_additive-number_test.go
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package _6_backtracking
import (
"github.com/smartystreets/goconvey/convey"
"strconv"
"testing"
)
// 累加数: https://leetcode.cn/problems/additive-number/description/
func TestIsAdditiveNumber(t *testing.T) {
convey.Convey("累加数:除了最开始的两个数以外,序列中的每个后续数字必须是它之前两个数字之和", t, func() {
testCase := []struct {
input string
target bool
}{
{
"112358",
true,
},
{
"199100199",
true,
},
}
for _, tst := range testCase {
rsp := isAdditiveNumber(tst.input)
convey.So(rsp, convey.ShouldEqual, tst.target)
}
})
}
// 输入视角(选/不选)
func isAdditiveNumber(num string) bool {
n := len(num)
var path []int
var ans [][]int // 列出所有组合
var dfs func(int, int)
dfs = func(i, start int) {
if i == n { // 最后一个一定得选
ans = append(ans, append([]int(nil), path...))
return
}
// 不选
if i < n-1 {
dfs(i+1, start)
}
if i-start > 0 && num[start] == '0' {
return
}
digit, _ := strconv.Atoi(num[start : i+1])
// 选
if len(path) < 2 || digit == path[len(path)-1]+path[len(path)-2] {
path = append(path, digit)
dfs(i+1, i+1)
path = path[:len(path)-1]
}
}
dfs(0, 0)
flag := false
for _, array := range ans {
if len(array) >= 3 { // 代表有组合
flag = true
break
}
}
return flag
}