-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution842.cs
72 lines (63 loc) · 1.99 KB
/
Solution842.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
using System.Text;
using LeetCode.DataStructures;
namespace LeetCode.Solutions;
public class Solution842
{
/// <summary>
/// 842. Split Array into Fibonacci Sequence - Medium
/// <a href="https://leetcode.com/problems/split-array-into-fibonacci-sequence">See the problem</a>
/// </summary>
public IList<int> SplitIntoFibonacci(string num)
{
var result = new List<int>();
if (Backtrack(num, 0, result))
{
return result;
}
return [];
}
private bool Backtrack(string num, int index, List<int> sequence)
{
if (index == num.Length && sequence.Count >= 3)
{
return true; // Valid sequence found
}
long currentNumber = 0;
for (int i = index; i < num.Length; i++)
{
// Prevent leading zeroes
if (i > index && num[index] == '0')
{
break;
}
// Form the current number
currentNumber = currentNumber * 10 + (num[i] - '0');
if (currentNumber > int.MaxValue)
{
break; // Number exceeds 32-bit integer limit
}
int currentInt = (int)currentNumber;
// Check if the sequence can continue
if (sequence.Count >= 2)
{
long sum = (long)sequence[sequence.Count - 1] + sequence[sequence.Count - 2];
if (currentNumber < sum)
{
continue; // Current number is too small
}
if (currentNumber > sum)
{
break; // Current number is too large
}
}
// Add the current number to the sequence and backtrack
sequence.Add(currentInt);
if (Backtrack(num, i + 1, sequence))
{
return true;
}
sequence.RemoveAt(sequence.Count - 1); // Backtrack
}
return false;
}
}