【Leetcode 每日一题】842. 将数组拆分成斐波那契序列(DFS)

Leetcode 每日一题
题目链接: 842. 将数组拆分成斐波那契序列
难度: 中等
解题思路: 用DFS进行搜索,判断是否为斐波那契数列。
题解:

class Solution:
    def splitIntoFibonacci(self, S: str) -> List[int]:
        
        res = list()

        def dfs(index):
            if index == len(S):
                return len(res) >= 3
            
            fibo_digit = 0
            for i in range(index, len(S)):
                if (i - index) > 0 and S[index] == "0": # 每个块数字不能以0开头
                    break
            
                # 找到一个可以组成斐波那契的数
                fibo_digit = fibo_digit * 10 + int(S[i])
                if fibo_digit > (1 << 31) - 1: # 数据范围
                    break
                

                if len(res) < 2 or fibo_digit == res[-2] + res[-1]:
                    res.append(fibo_digit)
                    
                    if dfs(i + 1):
                        return True
                    
                    res.pop()
                
                elif len(res) > 2 and fibo_digit > res[-2] + res[-1]:
                    break

            return False
        
        if dfs(0):
            return res
        else:
            return []


你可能感兴趣的:(Leetcode,leetcode,dfs,算法,字符串)