Additive Number
加法数
思路:一开始以为要用DP来做,但是这道题除非能保证每个相加数的划分是唯一的(事实上不是唯一的),否则只能用搜索。
1 public class Solution { 2 public boolean isAdditiveNumber(String num) { 3 for (int firstEnd = 0; firstEnd <= num.length() - 3; firstEnd++) { 4 if (num.charAt(0) == '0' && firstEnd > 0) { 5 break; 6 } 7 for (int secondEnd = firstEnd + 1; secondEnd <= num.length() - 2; secondEnd++) { 8 if (num.charAt(firstEnd + 1) == '0' && secondEnd > firstEnd + 1) { 9 break; 10 } 11 long first = Long.parseLong(num.substring(0, firstEnd + 1)); 12 long second = Long.parseLong(num.substring(firstEnd + 1, secondEnd + 1)); 13 if (helper(num, secondEnd + 1, first + second, second)) { 14 return true; 15 } 16 } 17 } 18 return false; 19 } 20 21 public boolean helper(String num, int start, long expect_num, long pre_num) { 22 if (start > num.length() - 1) { 23 return true; 24 } 25 if (num.charAt(start) == '0' && expect_num != 0) { 26 return false; 27 } 28 int end = start + String.valueOf(expect_num).length() - 1; 29 if (end + 1 > num.length()) { 30 return false; 31 } 32 long cur = Long.parseLong(num.substring(start, end + 1)); 33 if (cur == expect_num) { 34 long next_expect = pre_num + cur; 35 return helper(num, end + 1, next_expect, cur); 36 } 37 return false; 38 } 39 }