Java递归版01背包

class Solutionx{
    private int memo[][];
    private int w[];
    private int v[];
    
    public int bestValue(int Index,int c){
         if(Index < 0||c < 0){
            return 0;
         }       
         if(memo[Index][c]!=-1){
         return memo[Index][c];
         }
         int res=bestValue(Index-1,c);
         if(c>=w[Index]){
          res=Math.max(res, bestValue(Index-1,c-w[Index])+v[Index]);
         }
         memo[Index][c]=res;
         return res;
    }
    public int kcap(){
    
       w=new int[]{0,4,2,3,5};
       v=new int[]{0,2,5,1,4};
       memo=new int[8][8];
       for(int i=0;i<8;++i){
         for(int j=0;j<8;++j){
         memo[i][j]=-1;
         }
       }
       return bestValue(4,7); 
   }
 }
 
 
 
 
 public class Mainx {
    public static void main(String[] args) {
        Solutionx space=new Solutionx();
        System.out.println(space.kcap());
    }
 }
 
原文地址:https://www.cnblogs.com/z2529827226/p/11623813.html