您的位置:首页 > 其它

算法设计与应用基础:第十四周(2)

2017-05-23 17:47 239 查看


474. Ones and Zeroes

Add to List

DescriptionHintsSubmissionsSolutions

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 
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 
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]
;


收获:空间复杂度的提高,不需要三维数组(在简单背包问题中对应于一维数组)只需要二维数组,注意一定要是简单背包问题。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: