[LeetCode] Ones and Zeroes

来源:互联网 发布:linux怎么解压缩 编辑:程序博客网 时间:2024/06/05 20:17

In the computer world, use restricted resource you have to generate maximum benefit is what we always want to pursue.

For now, suppose you are a dominator of m 0s and n 1s respectively. On the other hand, there is an array with strings consisting of only 0s and 1s.

Now your task is to find the maximum number of strings that you can form with given m 0s and n 1s. Each 0 and 1 can be used at most once.

动态规划总是最恶心的,本题将中间信息存储在一个二维数组中,每拿到一个字符串,动态更新dp[][] 。

public class Solution {//首先 题目可有剩余   不然需要if((j==num0&&k==num1)||dp[j-num0][k-num1]!=0)//不断动态更新dp[][]  要从后向前更新  因为每个字符串只能用一次 如果从前往后更新 前面额更新结果会对后面造成干扰 //这个道理和01背包以及完全背包的区别是一样的 如果从前往后更新本题的题意将变为每个字符串可以用无数次 public int findMaxForm(String[] strs, int m, int n) {        int[][] dp=new int[m+1][n+1];        for(int i=0;i<strs.length;i++){        int num0=0,num1=0;        for(int k=0;k<strs[i].length();k++){        if(strs[i].charAt(k)=='0') num0++;        else if(strs[i].charAt(k)=='1') num1++;        }        for(int j=m;j>=num0;j--){        for(int k=n;k>=num1;k--){//         if((j==num0&&k==num1)||dp[j-num0][k-num1]!=0)        dp[j][k]=Math.max(dp[j][k],dp[j-num0][k-num1]+1);         }        }        }        return dp[dp.length-1][dp[0].length-1];    }}

注意: 要从后向前更新  因为每个字符串只能用一次,如果从前往后更新 前面额更新结果会对后面造成干扰,这个道理和01背包以                  及完全背包的区别是一样的,如果从前往后更新本题的题意将变为每个字符串可以用无数次

原创粉丝点击