An additive number is a string whose digits can form an 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, return true if it is an additive number or false otherwise.
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
func isAdditiveNumber(num string) bool {
nums := make([]int, len(num))
for i := 0; i < len(num); i++ {
nums[i] = int(num[i])-48
}
count := 0
backtrack(nums, nil, &count)
if count == 0 {
return false
}
return true
}
func backtrack(nums, track []int, count *int) {
if !judge(track) {
return
}
if len(nums) == 0 && len(track) >= 3{
*count++
return
}
for i :=0; i < len(nums); i++ {
if i!=0 && nums[0] == 0 {
return
}
numscopy := append([]int{}, nums...)
trackcopy := append([]int{}, track...)
backtrack(numscopy[i+1:], append(trackcopy, transfer(numscopy[:i+1])) ,count )
}
}
func judge(track []int) bool {
if len(track) <= 2 {
return true
}
length := len(track)
if track[length-1] != track[length-2] + track[length-3] {
return false
}
return true
}
func transfer(data []int) int {
count :=0
for i:=0; i < len(data); i++ {
count = count * 10 + data[i]
}
return count
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。