306. Additive Number LeetCode
2016-03-16 17:56
387 查看
题意:给出一个只包含数字的字符串,问是否可以分成至少3个数,前两个数相加等于第三个数。
题解:枚举前两项,有了前两项就可以递推出后面的值,然后递推到跟原字符串长度相等的时候停止,然后比较是否相等,相等说明可以。
题解:枚举前两项,有了前两项就可以递推出后面的值,然后递推到跟原字符串长度相等的时候停止,然后比较是否相等,相等说明可以。
class Solution { public: bool isAdditiveNumber(string num) { int n = num.length(); for(int i = 1; i < n; i++) { for(int j = i + 1; j < n; j++) { string s1 = num.substr(0,i); string s2 = num.substr(i,j - i); long long d1 = atoll(s1.c_str()); long long d2 = atoll(s2.c_str()); if((s1.length() > 1 && s1[0] == '0') || (s2.length() > 1 && s2[0] == '0')) continue; long long next = d1 + d2; string nxt = to_string(next); string now = s1 + s2 + nxt; while(now.length() < num.length()) { d1 = d2; d2 = next; next = d1 + d2; nxt = to_string(next); now += nxt; } if(now == num) return true; } } return false; } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解