1. 程式人生 > >474. Ones and Zeroes

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

翻譯:

在計算機世界中,使用有限的資源,你必須產生最大的利益是我們一直想追求的。
現在,假設你是一個支配M 0和1分別。另一方面,有一個只有0和1組成的字串陣列。
現在你的任務是找到可以形成了M 0和1的最大字串數。每0和1可以用在最一次。
注:
給定數字0和1都將不超過100
給定字串陣列的大小不會超過600。
例1:
輸入:陣列= {“10”,“0001”,“111001”,“1”,“0”},m = 5,N = 3
輸出:4
說明:這是4個字串可以由5個0和3 1秒的使用形成的,這是“10”,“0001”、“1”、“0”
例2:
輸入:陣列= {“10”,“0”,“1”},m = 1,N = 1
輸出:2
說明:你可以形成“10”,但是你什麼都沒有了。更好地形成“0”和“1”。

解題程式碼:

#include<iostream>
#include<vector>
#include<string>

using namespace std; 

class Solution {
public:
    int findMaxForm(vector<string>& strs, int m, int n) {

        vector< vector<int> > dp(m+1, vector<int>(n+1,0));
		int zeros ,ones ;
		for(int i = 0; i< strs.size(); i++) {
			zeros = ones = 0;
			for(int j = 0; j < strs[i].length(); j++) {
				if(strs[i][j] == '0') zeros++;
				else ones++;
			}
			
			for(int a = m; a >= zeros; a--) {
				for(int b = n; b >= ones; b--) {
					dp[a][b] = max( dp[a][b], dp[a-zeros][b-ones]+1 );//一定要從後往前,否則一旦小範圍的被賦值,更大範圍的會再次賦值累積到很多會發生錯誤
					 
				}
			}
			
			
		} 
		return dp[m][n];
    }
};

int main() {
	string strs[] = {"10", "0001", "111001", "1", "0"};
	vector<string> v(strs,strs+ 5);
	Solution s;
	cout << s.findMaxForm(v, 5, 3) <<endl;
}

題目狀態: