link
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:
代码语言:javascript复制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
代码语言:javascript复制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
}