【Leetcode】474. Ones and Zeroes
Today, Leet weekly contest was hold on time. However, i was late about 15 minutes for checking out of the hotel.
It seems like every thing gone well. First problem was accepted by my first try. Second problem is not a complex task but has many coding work to solve it.
What makes me feel fool is the third problem which is absolutely a dp problem using two dimensions array. I was solved it by greedy. WTF, the reason of that I think may be I look down upon this problem.
I hope to solve it in easy stpes but I didn't think over it's weakness.
474. Ones and Zeroes
- User Accepted: 171
- User Tried: 359
- Total Accepted: 175
- Total Submissions: 974
- Difficulty: Medium
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:
- The given numbers of
0sand1swill both not exceed100 - 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".
class Solution { public: int findMaxForm(vector<string>& strs, int m, int n) { vector<vector<int>>dp(m + 1, vector<int>(n + 1, 0)); int len = strs.size(); for(int i = 0; i < len; i ++){ int z = 0, o = 0; for(auto &ch : strs[i]){ if(ch == '0') z ++; else o ++; } for(int j = m; j >= z; j --){ for(int k = n; k >= o; k --){ dp[j][k] = max(dp[j][k], dp[j - z][k - o] + 1); } } } int ret = 0; for(int i = 0; i <= m; i ++) for(int j = 0; j <= n; j ++) ret = max(ret, dp[i][j]); return ret; } };
浙公网安备 33010602011771号