306.additive-number.go 917 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. func isAdditiveNumber(num string) bool {
  2. n := len(num)
  3. if n < 3 { // At least 3 chars
  4. return false
  5. }
  6. for i := 1; i < (n+1)/2; i++ {
  7. if num[0] == '0' && i != 1 { // Avoid 00 + ...
  8. return false
  9. }
  10. for j := 1; j <= (n-i)/2; j++ {
  11. if num[i] == '0' && j != 1 { // Avoid ... + 0x
  12. break
  13. }
  14. var one, two int
  15. fmt.Sscan(num[0:i], &one)
  16. fmt.Sscan(num[i:i+j], &two)
  17. if search(num, i+j, one, two) {
  18. return true
  19. }
  20. }
  21. }
  22. return false
  23. }
  24. func search(num string, idx, one, two int) bool {
  25. n := len(num)
  26. if idx == n {
  27. return true
  28. } else if num[idx] == '0' {
  29. if one+two != 0 {
  30. return false
  31. }
  32. return search(num, idx+1, 0, 0) // 00000000... is valid
  33. }
  34. var three int
  35. for three = 0; three < one+two && idx < n; idx++ {
  36. three = three*10 + int(num[idx]-'0')
  37. }
  38. if three == one+two {
  39. return search(num, idx, two, three)
  40. }
  41. return false
  42. }
  43. type pair struct {
  44. _1 int
  45. _2 int
  46. }