[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]

posted @ 2022-04-06 11:50  frankming  阅读(15)  评论(0编辑  收藏  举报