0-1 knapsack

递归 注释记忆化搜索

10背包

测试用例 背包大小5

10背包

耗时

10背包

添加记忆化搜索

10背包
10背包
package main

import (
    "fmt"
    "time"
)

func findbv(remainpack int,putted map[int]bool,curv int,kv [][]int,memo map[int]int) int{
    max:=curv
    for k,v:=range kv {
        if _,ok:=memo[remainpack];ok {
            if memo[remainpack]>max {
                fmt.Println("hit")
                max=memo[remainpack]
            }
        } else
        if remainpack-v[0]>=0 && putted[k]!=true {
            putted[k]=true
            a:=findbv(remainpack-v[0],putted,curv+v[1],kv,memo)
            putted[k]=false
            if max
example :[w,v] [1,6] [2,10] [3,12]    pack: 5


greedy algorithm 近似最优

put bigger v/w into pack first until overflow


recusive + memorization   


findBiggestV(remainPack , putted,currV)


iterate all remainkvpair
    if memo[remainpack]
        return memo[remainpack]
    if remainpack-k>=0 && !putted
        putted[k]=true
        tmpc = currV+v
        currV = max(findBiggest(remainPack-k,tmpc) ,currV)

memo[remainpack]=currv
return currV


dynamic programming


你可能感兴趣的:(0-1 knapsack)