算法设计与应用基础:第十四周(2)
2017-05-23 17:47
239 查看
474. Ones and Zeroes
Add to ListDescriptionHintsSubmissionsSolutions
Total Accepted: 9440
Total Submissions: 24868
Difficulty: Medium
Contributors:piy9
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
0sand n
1srespectively.
On the other hand, there is an array with strings consisting of only
0sand
1s.
Now your task is to find the maximum number of strings that you can form with given m
0sand n
1s.
Each
0and
1can
be used at most once.
Note:
The given numbers of
0sand
1swill
both not exceed
100
The size of given string array won't exceed
600.
解题思路:也是背包问题的变式,只不过将重量转变为0和1的个数,状态转移方程为dp[p][j]=max(dp[p-helper[i-1][0]][j-helper[i-1][1]]+1,dp[p][j]);
代码为:
int findMaxForm(vector<string>& strs, int m, int n) { int size=strs.size(); int helper[size][2]; memset(helper,0,sizeof(helper)); for(int i=0;i<strs.size();i++) { int t1=0,t0=0; for(int p=0;p<strs[i].size();p++) { if(strs[i][p]=='0') t0++; else t1++; } helper[i][0]=t0; helper[i][1]=t1; } int dp[m+1][n+1]; memset(dp,0,sizeof(dp)); for(int i=1;i<=size;i++) { for(int p=m;p>=helper[i-1][0];p--) { for(int j=n;j>=helper[i-1][1];j--) { dp[p][j]=max(dp[p-helper[i-1][0]][j-helper[i-1][1]]+1,dp[p][j]); //else // dp[i][p][j]=max(dp[i-1][p][j],dp[i][p][j]); //cout<<i<<" "<<p<<" "<<j<<" "<<dp[i][p][j]<<endl; } } } return dp[m] ;
收获:空间复杂度的提高,不需要三维数组(在简单背包问题中对应于一维数组)只需要二维数组,注意一定要是简单背包问题。
相关文章推荐
- 算法设计与应用基础:第十四周(1)
- 算法设计与应用基础:第十四周
- 算法设计与应用基础-第一周题目
- 算法设计与应用基础 - Week01
- 算法设计与应用基础:第一周
- 算法设计与应用基础: 第四周(1)
- 算法设计与应用基础: 第七周(1)
- 算法设计与应用基础: 第三周(3)
- 算法设计与应用基础: 第三周(1)
- 算法设计与应用基础-第四周
- 算法设计与应用基础: 第三周(2)
- 算法设计与应用基础:第七周
- 算法设计与应用基础:第一周(3)
- 算法设计与应用基础: 第五周(1)
- 算法设计与应用基础-第三周
- 算法设计与应用基础作业(三)
- 算法设计与应用基础:第二周(1)
- 算法设计与应用基础:第二周(2)
- 算法设计与应用基础-第六周
- 算法设计与应用基础: 第六周(1)