Google面试题专题6 - leetcode230. Kth Smallest Element in a BST/139. Word Break

230. Kth Smallest Element in a BST

题目描述

给定一颗二叉搜索树,编写函数kthSmallest找到第k小元素。(1 ≤ k ≤ BST的总元素个数)

例子
Example 1:
Input: root = [3,1,4,null,2], k = 1
Output: 1

Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3
Output: 3

思想
中序遍历,感觉还可以优化
解法
中序遍历(递归)。复杂度:时间 - O(n),空间 - O(n)

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def kthSmallest(self, root, k):
        """
        :type root: TreeNode
        :type k: int
        :rtype: int
        """
        res = []
        
        def inOrder(root, res):
            if root:
                inOrder(root.left, res)
                res.append(root.val)
                if len(res) == k:
                    return
                inOrder(root.right, res)
        
        inOrder(root, res)
        return res[k-1]

中序遍历(非递归)。

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def kthSmallest(self, root, k):
        """
        :type root: TreeNode
        :type k: int
        :rtype: int
        """
        stack = []
        while stack or root:
            while root:
                stack.append(root)
                root = root.left
            node = stack.pop()
            k -= 1
            if k == 0:
                return node.val
            root = node.right
139. Word Break

题目描述

给定一非空字符串s和一包含非空单词列表的wordDict。判断s是否可以拆分成wordDict的单词表示?

wordDict中的同一个单词可以被使用多次。

例子
Example 1:

Input: s = “leetcode”, wordDict = [“leet”, “code”]
Output: true

Explanation: Return true because “leetcode” can be segmented as “leet code”.

Example 2:

Input: s = “applepenapple”, wordDict = [“apple”, “pen”]
Output: true

Explanation: Return true because “applepenapple” can be segmented as “apple pen apple”. Note that you are allowed to reuse a dictionary word.

Example 3:

Input: s = “catsandog”, wordDict = [“cats”, “dog”, “sand”, “and”, “cat”]
Output: false

思想
(法1 - DFS)
(法2 - DP)
dp[i]表示到s[:i]是否可以由wordDict表示。
转移方程:for j in range(i): if dp[j] and s[j:i] in wordDict: dp[i] = True
或 for w in wordDict: if dp[i-len(w)] and s[i-len(w):i] == w: dp[i] = True

解法1
DFS,TLE

class Solution(object):
    def wordBreak(self, s, wordDict):
        """
        :type s: str
        :type wordDict: List[str]
        :rtype: bool
        """
        if not s:
            return True
        for i in range(len(s)):
            if s[:i+1] in wordDict:
                if self.wordBreak(s[i+1:], wordDict):
                    return True
        return False

解法2
DP。复杂度:时间 - O(n^2),空间O(n)。

class Solution(object):
    def wordBreak(self, s, wordDict):
        """
        :type s: str
        :type wordDict: List[str]
        :rtype: bool
        """
        n = len(s)
        wordDict = set(wordDict)
        dp = [False] * (n + 1)
        dp[0] = True
        
        for i in range(1, n+1):
            for j in range(i):
                if dp[j] and s[j:i] in wordDict:
                    dp[i] =  True
                    break
        return dp[-1]
class Solution(object):
    def wordBreak(self, s, wordDict):
        """
        :type s: str
        :type wordDict: List[str]
        :rtype: bool
        """
        n = len(s)
        dp = [False] * (n + 1)
        dp[0] = True
        
        for i in range(1, n+1):
            for w in wordDict:
                if dp[i-len(w)] and s[i-len(w):i] == w:
                    dp[i] = True
                    break
        return dp[-1]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值