1
+ // Runtime: 0 ms (Top 100.0%) | Memory: 7.80 MB (Top 37.58%)
2
+
1
3
class Solution {
2
4
public:
5
+ vector<int > ans;
6
+
7
+ bool getFibo (string &s,int i,long a,long b,int n) {
8
+ if (i==s.length ()) return n>2 ;
9
+
10
+ long num=0 ;
11
+ for (int x=i;x<s.length ();x++) {
12
+ num= num*10 +s[x]-' 0' ;
13
+ if (num>INT_MAX) break ;
14
+
15
+ bool chk=false ;
16
+ ans.push_back (num);
17
+ if (n<2 ) chk=getFibo (s,x+1 ,b,num,n+1 );
18
+ else if (a+b==num) chk= getFibo (s,x+1 ,b,num,n+1 );
19
+ if (chk) return true ;
20
+ ans.pop_back ();
21
+
22
+ if (num==0 ) break ;
23
+ }
24
+ return false ;
25
+ }
3
26
4
- vector<int > res;
5
-
6
- void backtrack (vector<int >& ans, string s, int curr) {
7
- // Basic check for end
8
- if (curr == s.size ()) {
9
- // if more than 3 elements in ans, BOOM, we got it!!
10
- if (ans.size () > 2 ) res = ans;
11
-
12
- // if not, purpose is not solved :( => return in both scenarios
13
- return ;
14
- }
15
-
16
- // start with current index to check possible string forming next fibbo seq no
17
- long val = 0 ; // stores possible generated numbers
18
- for (int i = curr; i < s.size (); ++i) {
19
- if (i > curr && s[curr] == ' 0' ) return ; // Handle 0 cases, 01, 02 cannot be considered
20
-
21
- val = val*10 + s[i] - ' 0' ;
22
- if (val > INT_MAX) return ;
23
-
24
- int n = ans.size ();
25
- if (ans.size () < 2 || val == (long )ans[n-1 ]+(long )ans[n-2 ]) {
26
- // val seems to be next fibbo seq no: insert to ans & go for next seq no
27
- ans.push_back (val);
28
- backtrack (ans, s, i+1 );
29
-
30
- // val seems to be failed to serve purpose: remove it from ans
31
- ans.pop_back ();
32
- }
33
- }
34
- }
35
-
36
- vector<int > splitIntoFibonacci (string num) {
37
- vector<int > ans;
38
-
39
- // Using recursive backtrack strating with 0
40
- backtrack (ans, num, 0 );
41
-
42
- return res;
43
- }
27
+ vector<int > splitIntoFibonacci (string S) {
28
+ ans.clear ();
29
+ getFibo (S,0 ,0 ,0 ,0 );
30
+ return ans;
31
+ }
44
32
};
0 commit comments