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]