[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 題目講解彙總(持續更新中...)

相關文章
相關標籤/搜索