首页 > 代码库 > 474. Ones and Zeroes
474. Ones and Zeroes
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 only0s
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 mostonce.
代码如下:(动态规划)
解析:
状态转换公式:dp[i][j]=Math.max(dp[i-a[0]][j-a[1]+1],dp[i][j])
public class Solution { public int findMaxForm(String[] strs, int m, int n) { if(m==0&&n==0) return 0; if(m<0||n<0) return 0; int[][] dp=new int[m+1][n+1]; for(int i=0;i<strs.length;i++) { String s=strs[i]; int[] a=abs(s); for(int j=m;j>=a[0];j--)//备忘录的自顶向下 { for(int k=n;k>=a[1];k--) { dp[j][k]=Math.max(dp[j-a[0]][k-a[1]]+1,dp[j][k]); } } } return dp[m][n]; } int[] abs(String s){ //用于统计每个字符串中0和1的个数 int[] a=new int[2]; for(int i=0;i<s.length();i++) { if(s.charAt(i)==‘0‘) a[0]++; else a[1]++; } return a; } }
474. Ones and Zeroes
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。