[LeetCode] Ones and Zeroes 一和零


  

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:

  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:

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:

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]可以達到的個數,我們跟其原有數值對比取較大值即可,所以遞推式如下:

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

 

類似題目:

Coin Change

 

參考資料:

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM