474. Ones and Zeroes
Posted 烁宝宝
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章
[leetcode-474-Ones and Zeroes]
[Algorithm] 474. Ones and Zeroes