Ones and Zeroes

题目链接:https://leetcode.com/problems...

knapsack problem,这里是最基本的01背包,把cost变成了二维的。
参考背包九讲:http://love-oriented.com/pack...

public class Solution {
    public int findMaxForm(String[] strs, int m, int n) {
        /* dp[k][i][j]: the maximum # of strings using i 0s and j 1s using strs[0,k]
         * reuse dp[k][i][j] for next level => dp[i][j]
         * value == 1, cost = # of 0s and # of 1s
         */
         int[][] dp = new int[m + 1][n + 1];
         for(String s : strs) {
             int zeros = 0, ones = 0;
             for(int i = 0; i < s.length(); i++) {
                 if(s.charAt(i) == '0') zeros++;
                 else ones++;
             }
             
             for(int i = m; i >= zeros; i--) {
                 for(int j = n; j >= ones; j--) {
                     dp[i][j] = Math.max(dp[i][j], dp[i - zeros][j - ones] + 1);
                 }
             }
         }
         
         return dp[m][n];
    }
}

lulouch13
13 声望6 粉丝

« 上一篇
Target Sum
下一篇 »
H-Index & II