[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背包以 及完全背包的区别是一样的,如果从前往后更新本题的题意将变为每个字符串可以用无数次
阅读全文
1 0
- LeetCode: Ones and Zeroes
- [LeetCode] Ones and Zeroes
- LeetCode 474. Ones and Zeroes
- [leetcode] 474. Ones and Zeroes
- LeetCode 474. Ones and Zeroes
- Leetcode-474. Ones and Zeroes
- [LeetCode]474. Ones and Zeroes
- 【LeetCode】 474. Ones and Zeroes
- Leetcode-474-Ones and Zeroes
- LeetCode 474. Ones and Zeroes
- [leetcode]474. Ones and Zeroes
- Leetcode 474. Ones and Zeroes
- LeetCode 474 Ones and Zeroes
- Leetcode 474 Ones and Zeroes
- Leetcode 474. Ones and Zeroes
- leetcode 474. Ones and Zeroes
- Leetcode 474 Ones and Zeroes
- [LeetCode] 474. Ones and Zeroes
- PyQt实现一个简单的License系统(二)
- 简单数据库操作(SQL)
- 分享一个导出excel的工具类
- Javascript:谈谈JS的全局变量跟局部变量
- 深度学习
- [LeetCode] Ones and Zeroes
- For Test
- SpringMVC拦截器的使用详解
- 图像分割系列文章
- 关于NIO的那些事儿
- 统计学习方法概述
- 解决 {"ret":100030,"msg":"this api without user authorization"} android QQ第三发登录成功后获取用户信息失败的问题
- 仿微信二维码扫描自定义view
- 定时器以及定时器事件