欢迎来到Cefler的博客😁
🕌博客主页:折纸花满衣
🏠个人专栏:题目解析
🌎推荐文章:【LeetCode】winter vacation training
目录
- 👉🏻一和零
👉🏻一和零
原题链接:一和零
mycode(超出时间限制):
class Solution {
public:int findMaxForm(vector<string>& strs, int m, int n) {int len = strs.size();//创建dp表vector<vector<vector<int>>> dp(len+1,vector<vector<int>>(m+1,vector<int>(n+1)));//三维dp表//dp表初始化,i、j、k轴初始化都是0可以省略这一步骤了//开始填表for(int i = 1;i<=len;i++){for(int j = 0;j<=m;j++){for(int k = 0;k<=n;k++){dp[i][j][k] = dp[i-1][j][k];map<char,int> num;for(auto e : strs[i-1]) num[e]++;//计算字符串中0和1的个数if(j-num['0']>=0&&k-num['1']>=0)dp[i][j][k] = max(dp[i-1][j][k],dp[i-1][j-num['0']][k-num['1']]+1);}}}return dp[len][m][n];}
};
时间优化:
class Solution {
public:int findMaxForm(vector<string>& strs, int m, int n) {int len = strs.size();//创建dp表vector<vector<vector<int>>> dp(len+1,vector<vector<int>>(m+1,vector<int>(n+1)));//三维dp表//dp表初始化,i、j、k轴初始化都是0可以省略这一步骤了//开始填表for(int i = 1;i<=len;i++){for(int j = 0;j<=m;j++){for(int k = 0;k<=n;k++){dp[i][j][k] = dp[i-1][j][k];int a = 0,b = 0;for(auto e : strs[i-1]){if(e=='0') a++;else b++;}if(j-a>=0&&k-b>=0)dp[i][j][k] = max(dp[i-1][j][k],dp[i-1][j-a][k-b]+1);}}}return dp[len][m][n];}
};
这里摒弃掉了map