[LeetCode] Ones and Zeroes 一和零

  

In the computer world, use restricted resource you have to generate maximum benefit is what we always want to pursue.html

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.java

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:数组

  1. The given numbers of 0s and 1s will both not exceed 100
  2. The size of given string array won't exceed 600.

 

Example 1:dom

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:post

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".

 

这道题是一道典型的应用DP来解的题,若是咱们看到这种求总数,而不是列出全部状况的题,十有八九都是用DP来解,重中之重就是在于找出递推式。若是你第一反应没有想到用DP来作,想得是用贪心算法来作,好比先给字符串数组排个序,让长度小的字符串在前面,而后遍历每一个字符串,遇到0或者1就将对应的m和n的值减少,这种方法在有的时候是不对的,好比对于{"11", "01", "10"},m=2,n=2这个例子,咱们将遍历完“11”的时候,把1用完了,那么对于后面两个字符串就无法处理了,而其实正确的答案是应该组成后面两个字符串才对。因此咱们须要创建一个二维的DP数组,其中dp[i][j]表示有i个0和j个1时能组成的最多字符串的个数,而对于当前遍历到的字符串,咱们统计出其中0和1的个数为zeros和ones,而后dp[i - zeros][j - ones]表示当前的i和j减去zeros和ones以前能拼成字符串的个数,那么加上当前的zeros和ones就是当前dp[i][j]能够达到的个数,咱们跟其原有数值对比取较大值便可,因此递推式以下:url

dp[i][j] = max(dp[i][j], dp[i - zeros][j - ones] + 1);spa

有了递推式,咱们就能够很容易的写出代码以下:
 
class Solution {
public:
    int findMaxForm(vector<string>& strs, int m, int n) {
        vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
        for (string str : strs) {
            int zeros = 0, ones = 0;
            for (char c : str) (c == '0') ? ++zeros : ++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];
    }
};

 

相似题目:rest

Coin Changecode

 

参考资料:

https://discuss.leetcode.com/topic/71438/c-dp-solution-with-comments

https://discuss.leetcode.com/topic/71417/java-iterative-dp-solution-o-mn-space

 

LeetCode All in One 题目讲解汇总(持续更新中...)

相关文章
相关标签/搜索