23.01 가방의 귀환 소환 & 동적 기획

public class HuiSuBag {

    //       
    private static int maxW = Integer.MIN_VALUE; //      maxW  
    private int[] weight = {2, 2, 4, 6, 3}; //     
    private int w = 9; //          

    public static void main(String[] args) {
        new HuiSuBag().f(0,0);
        System.out.println(maxW);
    }

    public void f(int i, int cw) { //    f(0, 0)
        if (cw == w || i == weight.length) { // cw==w      ,i==weight.length          
            if (cw > maxW) {
                maxW = cw;
            }
            return;
        }
        f(i + 1, cw); //       i    
        if (weight[i] + cw <= w) {
            f(i + 1, cw + weight[i]);
        }
    }
    
 	public int dp() {
        int[][] dp = new int[weight.length][w + 1];
        dp[0][0] = 1;
        dp[0][weight[0]] = 1;
        for (int i = 1; i < weight.length; i++) {
            for (int j = 0; j < w + 1; j++) {
                if (dp[i - 1][j] == 1) {
                    dp[i][j] = 1;
                    if (j + weight[i] <= w) {
                        dp[i][j + weight[i]] = 1;
                    }
                }
            }
        }
        int result = 0;
        for (int i = w; i >= 0; i--) {
            if (dp[weight.length - 1][i] == 1) {
                result = Math.max(result, i);
            }
        }
        return result;
    }
}

좋은 웹페이지 즐겨찾기