完全背包
def material_bag ( N, V, weight, value) :
dp = [ 0 ] * ( V+ 1 )
for i in range ( N) :
for j in range ( weight[ i] , V+ 1 ) :
dp[ j] = max ( dp[ j] , dp[ j- weight[ i] ] + value[ i] )
return dp[ V]
if __name__== '__main__' :
N, V = map ( int , input ( ) . split( ) )
weight = [ ]
value = [ ]
for i in range ( N) :
a, b = input ( ) . split( )
weight. append( int ( a) )
value. append( int ( b) )
result = material_bag( N, V, weight, value)
print ( result)
518. 零钱兑换 II
class Solution ( object ) :
def change ( self, amount, coins) :
"""
:type amount: int
:type coins: List[int]
:rtype: int
"""
dp = [ 0 ] * ( amount+ 1 )
dp[ 0 ] = 1
for coin in coins:
for j in range ( coin, amount+ 1 ) :
dp[ j] += dp[ j- coin]
return dp[ amount]
377. 组合总和 Ⅳ
class Solution ( object ) :
def combinationSum4 ( self, nums, target) :
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
dp = [ 0 ] * ( target+ 1 )
dp[ 0 ] = 1
for j in range ( 1 , target+ 1 ) :
for num in nums:
if j >= num:
dp[ j] += dp[ j- num]
return dp[ target]
70. 爬楼梯 (进阶)
def climb_stairs ( n, m) :
dp= [ 0 ] * ( n+ 1 )
dp[ 0 ] = 1
for j in range ( 1 , n+ 1 ) :
for i in range ( 1 , m+ 1 ) :
if j>= i:
dp[ j] += dp[ j- i]
return dp[ n]
if __name__== '__main__' :
n, m = map ( int , input ( ) . split( ) )
result = climb_stairs( n, m)
print ( result)