1.买卖股票的最佳时期
class Solution ( object ) :
def maxProfit ( self, prices) :
"""
:type prices: List[int]
:rtype: int
"""
ans = 0
minPrice = prices[ 0 ]
for i in range ( len ( prices) ) :
minPrice = min ( minPrice, prices[ i] )
ans = max ( ans, prices[ i] - minPrice)
return ans
2.跳跃游戏
class Solution ( object ) :
def canJump ( self, nums) :
"""
:type nums: List[int]
:rtype: bool
"""
max_i = 0
for i in range ( len ( nums) ) :
if max_i >= i and max_i < i+ nums[ i] :
max_i = i + nums[ i]
return max_i >= len ( nums) - 1
3.跳跃游戏II
class Solution ( object ) :
def jump ( self, nums) :
"""
:type nums: List[int]
:rtype: int
"""
n = len ( nums)
maxPos, end, step = 0 , 0 , 0
for i in range ( n - 1 ) :
if maxPos >= i:
maxPos = max ( maxPos, i + nums[ i] )
if i == end:
end = maxPos
step += 1
return step
4.划分字母区间
class Solution ( object ) :
def partitionLabels ( self, s) :
"""
:type s: str
:rtype: List[int]
"""
last = { }
for i in range ( len ( s) ) :
last[ s[ i] ] = i
res = [ ]
start, end = 0 , 0
for i in range ( len ( s) ) :
end = max ( end, last[ s[ i] ] )
if i == end:
res. append( end - start + 1 )
start = end + 1
return res
5.爬楼梯
class Solution ( object ) :
def climbStairs ( self, n) :
"""
:type n: int
:rtype: int
"""
dp = [ 0 ] * ( n + 1 )
dp[ 0 ] = 1
dp[ 1 ] = 1
for i in range ( 2 , len ( dp) ) :
dp[ i] = dp[ i - 1 ] + dp[ i - 2 ]
return dp[ n]
6.杨辉三角形
代码链接 注意这里的问题是动态规划的矩阵不是我们要返回结果的答案
class Solution ( object ) :
def generate ( self, numRows) :
"""
:type numRows: int
:rtype: List[List[int]]
"""
if numRows == 1 : return [ [ 1 ] ]
dp = [ [ 1 ] * numRows for _ in range ( numRows) ]
res = [ ]
res. append( [ 1 ] )
for i in range ( 1 , numRows) :
level = [ 1 ]
for j in range ( 1 , i) :
dp[ i] [ j] = dp[ i- 1 ] [ j- 1 ] + dp[ i- 1 ] [ j]
level. append( dp[ i] [ j] )
level. append( 1 )
res. append( level)
return res
7.打家劫舍
class Solution ( object ) :
def rob ( self, nums) :
"""
:type nums: List[int]
:rtype: int
"""
if len ( nums) == 1 : return nums[ 0 ]
dp = [ 0 ] * len ( nums)
dp[ 0 ] = nums[ 0 ]
dp[ 1 ] = max ( nums[ 0 ] , nums[ 1 ] )
for i in range ( 2 , len ( nums) ) :
dp[ i] = max ( dp[ i- 1 ] , dp[ i- 2 ] + nums[ i] )
return dp[ - 1 ]