File tree Expand file tree Collapse file tree 1 file changed +24
-0
lines changed
Expand file tree Collapse file tree 1 file changed +24
-0
lines changed Original file line number Diff line number Diff line change 1+ # -*- coding: utf-8 -*-
2+
3+ class Solution :
4+ # @param m: An integer m denotes the size of a backpack
5+ # @param A: Given n items with size A[i]
6+ # @return: The maximum size
7+ def backPack (self , m , A ):
8+ # write your code here
9+ '''
10+ 动态规划,已m = 10,A = [3, 4, 8, 5]为例:
11+ 1. A[0] = 3, c[10] ... C[3] = 3
12+ 2. A[1] = 4
13+ - c[10] = max(c[10 - 4] + 4, c[10]) = max(c[6] + 4, c[10]) = 7
14+ - c[7] = c[8] = c[9] = 7
15+ - c[6] = max(c[6 - 4] + 4, c[6]) = 4
16+ - c[4] = c[5] = 4
17+ c[i]表示大小为i的空间的最大容量,对于大小为k的物品,状态转移方程为:c[i] = max(c[i - k] + k, c[i])
18+ '''
19+ capacities = [0 ] * (m + 1 )
20+ if A :
21+ for i in xrange (len (A )):
22+ for j in xrange (m , A [i ] - 1 , - 1 ):
23+ capacities [j ] = max (capacities [j - A [i ]] + A [i ], capacities [j ])
24+ return capacities [- 1 ]
You can’t perform that action at this time.
0 commit comments