78. Subsets
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: nums = [1,2,3]
Output:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
思路:DFS
class Solution:
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
ans = [[]]
def solve(begin, current):
for i in range(begin, len(nums)):
ans.append(current+[nums[i]])
solve(i+1, current+[nums[i]])
solve(0, [])
return ans
Beat 93.67% python3 2018-05-13
优化:少算一次+
class Solution:
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
ans = []
def solve(begin, current):
ans.append(current)
for i in range(begin, len(nums)):
solve(i+1, current+[nums[i]])
solve(0, [])
return ans
Beat 100.0% python3 2018-05-13
79. Word Search
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example:
board =
[
[‘A’,’B’,’C’,’E’],
[‘S’,’F’,’C’,’S’],
[‘A’,’D’,’E’,’E’]
]
Given word = “ABCCED”, return true.
Given word = “SEE”, return true.
Given word = “ABCB”, return false.
思路:dfs,往四个方向移动试图找到字符串,走过的地方改成特殊字符,防止转圈。
class Solution:
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
if len(word) == 0:
return True
num_row, num_col = len(board), len(board[0])
if num_row == 0 or num_col == 0:
return False
moves = [ (1, 0), (-1, 0), (0, 1), (0, -1) ]
def dfs(r, c, index):
if board[r][c] != word[index]:
return False
if index + 1 == len(word):
return True
ch = board[r][c]
board[r][c] = '#'
for mv in moves:
rr, cc = r + mv[0], c + mv[1]
if rr >= 0 and rr < num_row and cc >= 0 and cc < num_col:
if dfs(rr, cc, index+1):
board[r][c] = ch
return True
board[r][c] = ch
return False
for i in range(len(board)):
for j in range(len(board[0])):
if dfs(i, j, 0):
return True
return False
Beat 20.92% python3 2018-05-13
优化:比较字符提前,减少进入dfs次数
class Solution:
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
if len(word) == 0:
return True
num_row, num_col = len(board), len(board[0])
if num_row == 0 or num_col == 0:
return False
moves = [ (1, 0), (-1, 0), (0, 1), (0, -1) ]
def dfs(r, c, index):
if index + 1 == len(word):
return True
ch = board[r][c]
board[r][c] = '#'
for mv in moves:
rr, cc = r + mv[0], c + mv[1]
if rr >= 0 and rr < num_row and cc >= 0 and cc < num_col:
if board[rr][cc] == word[index+1] and dfs(rr, cc, index+1):
board[r][c] = ch
return True
board[r][c] = ch
return False
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == word[0] and dfs(i, j, 0):
return True
return False
Beat 97.14% python3 2018-05-13
class Solution:
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
def dfs(r, c, index):
if index + 1 == len(word):
return True
ch = board[r][c]
board[r][c] = '#'
if r+1 < num_row and board[r+1][c] == word[index+1] and dfs(r+1, c, index+1):
return True
if c+1 < num_col and board[r][c+1] == word[index+1] and dfs(r, c+1, index+1):
return True
if r-1 >= 0 and board[r-1][c] == word[index+1] and dfs(r-1, c, index+1):
return True
if c-1 >= 0 and board[r][c-1] == word[index+1] and dfs(r, c-1, index+1):
return True
board[r][c] = ch
return False
if len(word) == 0:
return True
num_row, num_col = len(board), len(board[0])
if num_row == 0 or num_col == 0 or len(word) > num_row*num_col:
return False
for i in range(num_row):
for j in range(num_col):
if board[i][j] == word[0] and dfs(i, j, 0):
return True
return False
优化:展开for 遍历四个方向,每个方向判断是否出界比较的量减少
Beat 99.56% python3 2018-05-13
64. Minimum Path Sum
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
Example:
Input:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.
思路:DP,
class Solution:
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
rows = len(grid)
cols = len(grid[0])
if rows == 0 or cols == 0:
return 0
dp = copy.deepcopy(grid)
for i in range(rows):
for j in range(cols):
if i == 0 and j == 0:
pass
elif i < 1:
dp[i][j] += dp[i][j-1]
elif j < 1:
dp[i][j] += dp[i-1][j]
else:
if dp[i-1][j] < dp[i][j-1]:
dp[i][j] += dp[i-1][j]
else:
dp[i][j] += dp[i][j-1]
return dp[rows - 1][cols - 1]
Beat 25.69% python3 2018-05-14
优化:复用grid列表
class Solution:
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
rows = len(grid)
cols = len(grid[0])
if rows == 0 or cols == 0:
return 0
for i in range(rows):
for j in range(cols):
if i == 0 and j == 0:
pass
elif i < 1:
grid[i][j] += grid[i][j-1]
elif j < 1:
grid[i][j] += grid[i-1][j]
else:
if grid[i-1][j] < grid[i][j-1]:
grid[i][j] += grid[i-1][j]
else:
grid[i][j] += grid[i][j-1]
return grid[-1][-1]
Beat 95.57% python3 2018-05-14
优化:0行和0列特殊处理,不在for循环里判断
class Solution:
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
rows = len(grid)
cols = len(grid[0])
if rows == 0 or cols == 0:
return 0
for i in range(1, rows):
grid[i][0] += grid[i-1][0]
for j in range(1, cols):
grid[0][j] += grid[0][j-1]
for i in range(1, rows):
for j in range(1, cols):
if grid[i-1][j] < grid[i][j-1]:
grid[i][j] += grid[i-1][j]
else:
grid[i][j] += grid[i][j-1]
return grid[-1][-1]
Beat 99.39% python3 2018-05-14
94. Binary Tree Inorder Traversal
Given a binary tree, return the inorder traversal of its nodes’ values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [1,3,2]
Follow up: Recursive solution is trivial, could you do it iteratively?
思路:DFS
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
def dfs(node):
if node == None:
return
dfs(node.left)
ans.append(node.val)
dfs(node.right)
ans = []
dfs(root)
return ans
Beat 99.45% python3 2018-05-14
121. Best Time to Buy and Sell Stock
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.
Example 1:
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.
Example 2:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
思路:记录当前最小值,遍历数组,如果当前指-最小值比ans更大,更新ans,如果当前值比最小值小,更新最小值
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) == 0:
return 0
small = prices[0]
ans = 0
for n in prices[1 : ]:
ans = max(n - small, ans)
small = min(n, small)
return ans
Beat 16.19% python3 2018-05-15
优化:不使用min,max函数
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) < 2:
return 0
small = prices[0]
ans = 0
for n in prices[1 : ]:
if ans < n - small:
ans = n - small
if small > n:
small = n
return ans
Beat 98.44% python3 2018-05-15
优化:先更新small
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) < 2:
return 0
small = prices[0]
ans = 0
for n in prices[1 : ]:
if small > n:
small = n
elif ans < n - small:
ans = n - small
return ans
Beat 100.0% python3 2018-05-15