[LeetCode] Ones and Zeroes

本文介绍了一种利用动态规划解决资源分配问题的方法,具体场景为如何使用有限数量的0和1来组合出一系列二进制字符串,目标是最大化可形成的字符串数量。

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背包以                  及完全背包的区别是一样的,如果从前往后更新本题的题意将变为每个字符串可以用无数次

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值