92背包问题
92背包问题
题解
想当年大一的时候什么背包都会,01多重混合,二进制优化,md现在01背包都费劲
//state: dp[i][j]前i个物品,j的重量,表示的最大价值
//function: dp[i][j] = max(dp[i-1][j], dp[i-1][j-A[i-1]]+A[i-1])
//intialize:dp = 0
//answer: dp[len(A)][m]
代码
package main /** * @param m: An integer m denotes the size of a backpack * @param A: Given n items with size A[i] * @return: The maximum size */ func backPack(m int, A []int) int { dp := make([][]int, len(A)+1) for i := range dp { dp[i] = make([]int, m+1) } for i := 1; i <= len(A); i++ { for j := 0; j <= m; j++ { //容量不够,不装 if j < A[i-1] { dp[i][j] = dp[i-1][j] } else { dp[i][j] = max(dp[i-1][j], dp[i-1][j-A[i-1]]+A[i-1]) } } } return dp[len(A)][m] } func max(a, b int) int { if a > b { return a } return b }