Ones and Zeroes
来源:互联网 发布:ebsco数据库 编辑:程序博客网 时间:2024/06/06 02:53
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.
Note:
The given numbers of 0s and 1s will both not exceed 100The size of given string array won't exceed 600.
Example 1:
Input: Array = {“10”, “0001”, “111001”, “1”, “0”}, m = 5, n = 3
Output: 4
Explanation: This are totally 4 strings can be formed by the using of 5 0s and 3 1s, which are “10,”0001”,”1”,”0”
Example 2:
Input: Array = {“10”, “0”, “1”}, m = 1, n = 1
Output: 2
Explanation: You could form “10”, but then you’d have nothing left. Better form “0” and “1”.
2.求解思路
使用动态规划进行求解.令A(k,m,n)表示前i个字符串,提供m个0和n个1所能达到的最大字符串个数,令ak表示第k个字符串中的0的个数,bk表示第k个字符串中1的个数,那么有如下状态转移方程:
A(k,m,n)= max(A(k-1,m-ak,n-bk)+1,A(k-1,m,n))
根据此方程来设计动态规划的代码.
3代码
class Solution{ public: int findMaxForm(vector<string>& strs,int m,int n){ vector<int> ones_num; vector<int> zeros_num; for(int i=0;i<strs.size();i++){ string s=strs[i]; int one_num=0; int zero_num=0; for(int j=0;j<s.size();j++){ if(s[j]=='1') one_num++; else zero_num++; } ones_num.push_back(one_num); zeros_num.push_back(zero_num); } vector<int> v(m+1,0); vector<vector<int>> table_before(n+1,v); table_before[ones_num[0]][zeros_num[0]]=1; for(int i=1;i<strs.size();i++){ vector<int> v(m+1,0); vector<vector<int>> table_next(n+1,v); for(int k=0;k<n+1;k++){ for(int j=0;j<m+1;j++){ int row = k-ones_num[i]; int col = j-zeros_num[i]; int x=INT_MIN; if(row>=0&&col>=0) x= x=table_before[row][col]+1; table_next[k][j]=max(table_before[k][j],x); } } table_before=table_next; } return table_before[n][m]; }};
- 474. Ones and Zeroes
- LeetCode: Ones and Zeroes
- Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- [LeetCode] Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 何给背景图像使用CSS3变形
- 播放常见问题分析
- CRC校验
- jQuery -- touch事件之轮播图效果
- disruptor总结
- Ones and Zeroes
- Android开发中的单位换算
- RN踩坑之 Windows下打包生成APK
- 上传附件,附件类型问题
- Android好文收藏
- iOS开发
- JVM CPU 占用率高分析
- 软件测试面试必备的一些基础理论概念
- cmake,静态库共享库