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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a786150017/article/details/84639541

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]

猜你喜欢

转载自blog.csdn.net/a786150017/article/details/84639541
今日推荐