Counting Bits
看看数
0 0 dp[0]=0
1 1 dp[1]=dp[1-1]+1
2 10 dp[2]=dp[2-2]+1
4 100 dp[4]=dp[4-4]+1
8 1000 dp[8]=dp[8-8]+1
动态规划:dp[i]=dp[i-offset]+1
代码:
class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
ans=[0]*(num+1)
offset=1
for i in xrange(1,num+1):
if offset*2==i:
offset<<=1
ans[i]=ans[i-offset]+1
return ans
413 Arithmetic Slices
用 dp[i] 来计算 最后为A[i]的Arithmetic Slices,i大于等于2是有意义
如果 A[i]-A[i-1]==A[i-1]-A[i-2]则表明 dp[i]=dp[i-1]+1;否则,dp[i]=0
class Solution(object):
def numberOfArithmeticSlices(self, A):
"""
:type A: List[int]
:rtype: int
"""
dp=[0]*len(A)
for i in range(2,len(A)):
if A[i]-A[i-1]==A[i-1]-A[i-2]:
dp[i]=dp[i-1]+1
return sum(dp)
然后,我们发现没有必要 用整个 列表,我们只需要知道前一个状态还有记录和:
class Solution(object):
def numberOfArithmeticSlices(self, A):
dp,ans=0,0
for i in range(2,len(A)):
if A[i]-A[i-1]==A[i-1]-A[i-2]:
dp+=1
ans+=dp
else:
dp=0
return ans
53 Maximum Subarray
经典题目,我用dp[i]来表示最后一位为nums[i]的最大子序列
则dp[i+1]=nums[i+1] or nums[i+1]+dp[i]
class Solution(object):
def maxSubArray(self, nums):
dp=nums
for i in range(1,len(nums)):
if dp[i-1]>0:
dp[i]=nums[i]+dp[i-1]
return max(dp)
仿照上例,把dp这个list变成一个数:
class Solution(object):
def maxSubArray(self, nums):
dp=nums[0]
ans=dp
for i in nums[1:]:
dp=max(i,dp+i)
ans=max(dp,ans)
return ans
卖股票:
121 Best Time to Buy and Sell Stock
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices)<=1:return 0
dp=0
low=prices[0]
for x in prices[1:]:
dp=max(dp,x-low)
low=min(low,x)
return dp
198 House Robber
房屋抢劫
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:return 0
dp=nums
if len(nums)>1:
dp[1]=max(nums[0],nums[1])
for i in range(2,len(nums)):
dp[i]=max(dp[i-2]+nums[i],dp[i-1])
return dp[-1]
修改后:
class Solution(object):
def rob(self, nums):
if not nums:return 0
d=nums[0]
if len(nums)==1:return d
p=max(nums[0],nums[1])
for i in nums[2:]:
d,p=p,max(d+i,p)
return p
discuss里:特别的精简
f(0) = nums[0]
f(1) = max(num[0], num[1])
f(k) = max( f(k-2) + nums[k], f(k-1) )
class Solution:
def rob(self, nums):
last, now = 0, 0
for i in nums: last, now = now, max(last + i, now)
return now