classSolution { public: intmaxEnvelopes(vector<vector<int>>& envelopes){ int n = envelopes.size(); if (n < 1) return0; sort(envelopes.begin(), envelopes.end(), cmp); int res = 1; vector<int> dp(n, 1); for (int i = 0; i < n; ++i) { for (int j = 0; j < i; ++j) { if (envelopes[j][1] < envelopes[i][1]) { dp[i] = max(dp[i], dp[j] + 1); } } res = max(res, dp[i]); } return res; }
staticboolcmp(const vector<int>& a, const vector<int>& b){ if (a[0] != b[0]) return a[0] < b[0]; return a[1] > b[1]; } };
方法1(python)
classSolution: defmaxEnvelopes(self, arr: List[List[int]]) -> int: n = len(arr) arr.sort(key=lambda x: (x[0], -x[1])) nums = [i[1] for i in arr] dp = [1] * n res = 0 for i inrange(n): for j inrange(i): if nums[j] < nums[i]: dp[i] = max(dp[i], dp[j] + 1) res = max(res, dp[i]) return res
方法2(c++)
classSolution { public: intmaxEnvelopes(vector<vector<int>>& envelopes){ int n = envelopes.size(); if (n < 1) return0; sort(envelopes.begin(), envelopes.end(), cmp); vector<int> dp(n+1, INT_MAX); int len = 0; for (int i = 0; i < n; ++i) { int idx = lower_bound(dp.begin(), dp.end(), envelopes[i][1]) - dp.begin(); dp[idx] = envelopes[i][1]; len = max(len, idx); } return len+1; }
staticboolcmp(const vector<int>& a, const vector<int>& b){ if (a[0] != b[0]) return a[0] < b[0]; return a[1] > b[1]; } };
方法2(python)
from bisect import bisect_left
classSolution: defmaxEnvelopes(self, arr: List[List[int]]) -> int: arr.sort(key=lambda x: (x[0], -x[1])) nums = [i[1] for i in arr] dp = [] for i inrange(len(nums)): idx = bisect_left(dp, nums[i]) if idx == len(dp): dp.append(nums[i]) else: dp[idx] = nums[i] returnlen(dp)