842. Split Array into Fibonacci Sequence
2024-08-28 21:12:31
Given a string S
of digits, such as S = "123456579"
, we can split it into a Fibonacci-like sequence [123, 456, 579].
Formally, a Fibonacci-like sequence is a list F
of non-negative integers such that:
0 <= F[i] <= 2^31 - 1
, (that is, each integer fits a 32-bit signed integer type);F.length >= 3
;- and
F[i] + F[i+1] = F[i+2]
for all0 <= i < F.length - 2
.
Also, note that when splitting the string into pieces, each piece must not have extra leading zeroes, except if the piece is the number 0 itself.
Return any Fibonacci-like sequence split from S
, or return []
if it cannot be done.
Example 1:
Input: "123456579"
Output: [123,456,579]
Example 2:
Input: "11235813"
Output: [1,1,2,3,5,8,13]
Example 3:
Input: "112358130"
Output: []
Explanation: The task is impossible.
Example 4:
Input: "0123"
Output: []
Explanation: Leading zeroes are not allowed, so "01", "2", "3" is not valid.
Example 5:
Input: "1101111"
Output: [110, 1, 111]
Explanation: The output [11, 0, 11, 11] would also be accepted.
Note:
1 <= S.length <= 200
S
contains only digits.
Approach #1: C++.
class Solution {
public:
vector<int> splitIntoFibonacci(string S) {
vector<int> nums;
helper(S, nums, 0);
return nums;
} bool helper(string S, vector<int>& nums, int start) {
int len = S.length();
// if we reached end of string & we have more than 2 elements
// in our sequence then return true
if (start >= len && nums.size() >= 3) return true;
// since '0' in beginning is not allowed therefore if the current char is '0'
// then we can use it alone only and cann't extend it by adding more chars at the back.
// otherwise we make take upto 10 chars (length og MAX_INT)
int maxLen = (S[start] == '0') ? 1 : 10; // Try getting a solution by forming a number with 'i' chars begging with 'start'
for (int i = 1; i <= maxLen && start + i <= S.size(); ++i) {
long long temp = stoll(S.substr(start, i));
if (temp > INT_MAX) return false;
int sz = nums.size();
// If fibonacci property is not satisfied then we cann't get a solution
if (sz >= 2 && nums[sz-1] + nums[sz-2] < temp) return false;
if (sz <= 1 || nums[sz-1] + nums[sz-2] == temp) {
nums.push_back(temp);
if (helper(S, nums, start+i))
return true;
nums.pop_back();
}
}
return false;
}
};
最新文章
- Tomcat服务启动成功,但访问index.jsp出错 (jspInit)
- Reading With Purpose: A grand experiment
- 编译fresco源码
- IntelliJ IDEA 的SVN配置与使用
- linux rdsktop 运程管理 windows
- C/C++笔试题(很多)
- C++学习26 运算符重载的概念和语法
- mybatis和hibernate区别和应用场景
- HDU1013_Digital Roots【大数】【水题】
- 【转】Ansys 13.0 flexlm not running完美解决方案
- ubuntu vim YCM
- js中this指向问题
- ASP.NET Core 一步步搭建个人网站(1)_环境搭建
- maven 引入外部jar包的几种方式(转)
- Swig--模板引擎
- eclise linux c mysql
- 深入分析Java Web技术内幕
- 小记 HTML5 file对象
- HDU 3371 Connect the Cities 最小生成树(和关于sort和qsort的一些小发现)
- 每日英语:Philippine Chapel Becomes a Medical Center