一维动态规划——字符串,可以使用dfs+cache,也可以改写为dp数组

91. 解码方法

难度中等

一条包含字母 A-Z 的消息通过以下映射进行了 编码 :

'A' -> "1"
'B' -> "2"
...
'Z' -> "26"

要 解码 已编码的消息,所有数字必须基于上述映射的方法,反向映射回字母(可能有多种方法)。例如,"11106" 可以映射为:

  • "AAJF" ,将消息分组为 (1 1 10 6)
  • "KJF" ,将消息分组为 (11 10 6)

注意,消息不能分组为  (1 11 06) ,因为 "06" 不能映射为 "F" ,这是由于 "6" 和 "06" 在映射中并不等价。

给你一个只含数字的 非空 字符串 s ,请计算并返回 解码 方法的 总数 。

题目数据保证答案肯定是一个 32 位 的整数。

 

示例 1:

输入:s = "12"
输出:2
解释:它可以解码为 "AB"(1 2)或者 "L"(12)。

示例 2:

输入:s = "226"
输出:3
解释:它可以解码为 "BZ" (2 26), "VF" (22 6), 或者 "BBF" (2 2 6) 。

示例 3:

输入:s = "06"
输出:0
解释:"06" 无法映射到 "F" ,因为存在前导零("6" 和 "06" 并不等价)。

class Solution:
    def numDecodings(self, s: str) -> int:
        n = len(s)        
        wordDict = {str(i) for i in range(1, 27)}        
        dp = [0] * (n+1)
        dp[0] = 1

        for i in range(1, n+1):
            if s[i-1] in wordDict:
                dp[i] = dp[i-1]
            if i >= 2 and s[i-2:i] in wordDict:
                dp[i] += dp[i-2]

        return dp[n]

 

使用dfs + cache也可以:  

class Solution:
    def numDecodings(self, s: str) -> int:
        n = len(s)        
        wordDict = {str(i) for i in range(1, 27)}
        self.cache = {n : 1}

        def dfs(index):
            if index in self.cache:
                return self.cache[index]
                        
            word = s[index]
            n1 = 0
            if word in wordDict:            
                n1 = dfs(index+1)

            n2 = 0
            if index + 1 < n:             
                word2 = s[index:index+2]
                if word2 in wordDict:
                    n2 = dfs(index+2)
            
            self.cache[index] = n1+n2
            return self.cache[index]
                
        return dfs(index=0)

  

 

140. 单词拆分 II

难度困难

给定一个字符串 s 和一个字符串字典 wordDict ,在字符串 s 中增加空格来构建一个句子,使得句子中所有的单词都在词典中。以任意顺序 返回所有这些可能的句子。

注意:词典中的同一个单词可能在分段中被重复使用多次。

 

示例 1:

输入:s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"]
输出:["cats and dog","cat sand dog"]

示例 2:

输入:s = "pineapplepenapple", wordDict = ["apple","pen","applepen","pine","pineapple"]
输出:["pine apple pen apple","pineapple pen apple","pine applepen apple"]
解释: 注意你可以重复使用字典中的单词。

示例 3:

输入:s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
输出:[]

 

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
        n = len(s)
        path = []
        wordDict = set(wordDict)
        def dfs(index):
            if index == n:
                self.ans.append(" ".join(path))
                return

            for i in range(index,  n):
                word = s[index:i+1]
                if word in wordDict:
                    path.append(word)
                    dfs(i+1)
                    path.pop()
            
        self.ans = []
        dfs(index=0)
        return self.ans

  

posted @ 2023-01-30 20:40  bonelee  阅读(25)  评论(0编辑  收藏  举报