LeetCode: 306. Additive Number
题目描述
Additive number is a string whose digits can form additive sequence.
A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.
Given a string containing only digits '0'-'9'
, write a function to determine if it’s an additive number.
Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03
or 1, 02, 3
is invalid.
Example 1:
Input: "112358"
Output: true
Explanation: The digits can form an additive sequence: 1, 1, 2, 3, 5, 8.
1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8
Example 2:
Input: "199100199"
Output: true
Explanation: The additive sequence is: 1, 99, 100, 199.
1 + 99 = 100, 99 + 100 = 199
Constraints:
-
num
consists only of digits '0'-'9'
. -
1 <= num.length <= 35
Follow up:
How would you handle overflow for very large input integers?
解题思路 —— 深度优先搜索
- 题目中提到数字可能越界,因此需要自己实现 大数加法
- 深度优先搜索遍历所有情况,判断是否存在满足题意的组合。
- 需要注意,每个组合的数字不能有前置
0
AC 代码
// 翻转 num
func reverse(num []byte) [] byte{
for i, j := 0, len(num)-1; i < j; i, j = i+1, j-1 {
num[i], num[j] = num[j], num[i]
}
return num
}
// 计算 lhv + rhv
func addNumber(lhv, rhv string) string {
var ans []byte
carry := 0
for i, j := (len(lhv)-1), (len(rhv)-1); i >= 0 || j >= 0 ||
carry != 0; i, j = i-1, j-1 {
if i >= 0 { carry += int(lhv[i] - '0') }
if j >= 0 { carry += int(rhv[j] - '0') }
ans = append(ans, byte(carry % 10) + '0')
carry /= 10
}
return string(reverse(ans))
}
// 判断数组中的元素是否是 "Additive Numbers"
func judge(arr []string) bool {
if len(arr) < 3 { return false }
for i := 0; i < len(arr) - 2; i++{
if addNumber(arr[i], arr[i+1]) != arr[i+2] {
return false
}
}
return true
}
// 深度优先搜索查找合适的组合
func dfs(num string, arr[] string) bool {
if len(num) == 0 {
return judge(arr)
}
for i := 1; i <= len(num); i++{
// 过滤非 ‘0’ 的前置 ‘0’
if i != 1 && num[0] == '0' { break }
arr = append(arr, num[0:i])
if dfs(num[i:], arr) {
return true
}
arr = arr[:len(arr)-1]
}
return false
}
func isAdditiveNumber(num string) bool {
return dfs(num, []string{})
}