leetcode刷题之旅——474. Ones and Zeroes

来源:互联网 发布:阿里云香港主机 编辑:程序博客网 时间:2024/05/19 11:48

        这道题目是典型的二维背包问题,在动态规划中为middle,通过率35%的一道中级题目。

题目大意:

        给定我们一个01字符串数组,然后给定我们固定的1的数量和0的数量。问的是我们最多可以用这些1和0,组成多少个字符串。固定的1和0的数目就是我们背包的体积,而每个字符串的价值都是1,而消耗的空间就是组成该字符串的1和0的数量,价值为都是1。

例子:

Example 1:

Input: Array = {"10", "0001", "111001", "1", "0"}, m = 5, n = 3Output: 4Explanation: 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 = 1Output: 2Explanation: You could form "10", but then you'd have nothing left. Better form "0" and "1".

算法:

        使用二重背包问题的解决方法。对于每一个字符串,统计0和1的个数,作为其占去的体积。对于其价值来说,全部都是1,因为是统计能组成字符串的个数。其状态转移方程为:

        

        for (int i=m; i>=zeros; i--)             for (int j=n; j>=ones; j--)                dp[i][j] = max(dp[i][j], dp[i-zeros][j-ones]+1);

代码:

class Solution {public:    int findMaxForm(vector<string>& strs, int m, int n)     {        vector<vector<int>> dp(m+1,vector<int>(n+1,0));            for (auto &s: strs) {        int ones = count(s.begin(), s.end(), '1');        int zeros= s.size()-ones;        for (int i=m; i>=zeros; i--)             for (int j=n; j>=ones; j--)                dp[i][j] = max(dp[i][j], dp[i-zeros][j-ones]+1);    }    return dp[m][n];    }};




0 0
原创粉丝点击