[leetcode] 91. Decode Ways
题目
An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.
- For example,
[1,3,5,7,9]
,[7,7,7,7]
, and[3,-1,-5,-9]
are arithmetic sequences.
Given an integer array nums
, return the number of arithmetic subarrays of nums
.
A subarray is a contiguous subsequence of the array.
Example 1:
Input: nums = [1,2,3,4]
Output: 3
Explanation: We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself.
Example 2:
Input: nums = [1]
Output: 0
Constraints:
1 <= nums.length <= 5000
-1000 <= nums[i] <= 1000
思路
动态规划,如果当前数值大于0,那么dp[i] = dp[i-1]
,如果当前十位数大于10且小于等于26,那么dp[i] += dp[i-2]
。
代码
python版本:
class Solution:
def numDecodings(self, s: str) -> int:
if not s or s[0] == '0':
return 0
dp = [0]*(len(s)+1)
dp[0:2] = 1, 1
for i in range(2, len(s)+1):
if int(s[i-1]) > 0:
dp[i] = dp[i-1]
if 26 >= int(s[i-2:i]) >= 10:
dp[i] += dp[i-2]
return dp[-1]
本文来自博客园,作者:frankming,转载请注明原文链接:https://www.cnblogs.com/frankming/p/16105748.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~