https://leetcode.com/problems/russian-doll-envelopes/ // Use map (Russian doll number -> vector of envelopes) to record results // For each envelope, check above map, and when fitting envelope which can hold current one is found, // no need to check more envelope as later envelope is with smaller size or smaller Russian doll number. bool lesser(const pair<int, int> &m1, const pair<int, int> &m2) { // sort function return m1.first < m2.first || (m1.first == m2.first && m1.second < m2.second); } class Solution { // Russian doll number -> vector of envelopes map<int, vector<pair<int, int>>> mp; map<int, vector<pair<int, int>>>::reverse_iterator itr; vector<pair<int, int>>::iterator vitr; // bool for whether best answer is reached bool fit; public: int maxEnvelopes(vector<pair<int, int>>& envelopes) { sort(envelopes.begin(), envelopes.end(), lesser); int vlen = envelopes.size(); if (vlen == 0) { return 0; } // loop from big envelope to small envelope for (int i=vlen-1; i>=0; i--) { // with the order of Russian doll, check whether current envelope can fit previous one for(itr = mp.rbegin(); itr != mp.rend(); ++itr) { fit = false; for (vitr = itr->second.begin(); vitr != itr->second.end(); ++vitr) { if (envelopes[i].first < (*vitr).first && envelopes[i].second < (*vitr).second) { // find fitting envelope, add one to Russian doll answer and record if (mp.find(itr->first + 1) == mp.end()) { vector<pair<int, int>> tmpvec; tmpvec.push_back(envelopes[i]); mp[itr->first + 1] = tmpvec; } else { mp[itr->first + 1].push_back(envelopes[i]); } fit = true; break; } } if (fit) { // if current envelope fit Russian doll, no need to check envelope with less answer break; } } if (itr == mp.rend()) { // if no fitting envelope, current envelope is with Russian doll answer 1 if (mp.find(1) == mp.end()) { vector<pair<int, int>> tmpvec; tmpvec.push_back(envelopes[i]); mp[1] = tmpvec; } else { mp[1].push_back(envelopes[i]); } } } // return the most Russian doll answer return mp.rbegin()->first; } };
时间: 2024-10-12 19:42:12