★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-cjzltemr-gh.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★You have a number of envelopes with widths and heights given as a pair of integers (w, h)
. One envelope can fit into another if and only if both the width and height of one envelope is greater than the width and height of the other envelope.html
What is the maximum number of envelopes can you Russian doll? (put one inside other)git
Note:
Rotation is not allowed.github
Example:微信
Input: [[5,4],[6,4],[6,7],[2,3]]
Output: 3 Explanation: The maximum number of envelopes you can Russian doll is ([2,3] => [5,4] => [6,7]).3
給定一些標記了寬度和高度的信封,寬度和高度以整數對形式 (w, h)
出現。當另外一個信封的寬度和高度都比這個信封大的時候,這個信封就能夠放進另外一個信封裏,如同俄羅斯套娃同樣。app
請計算最多能有多少個信封能組成一組「俄羅斯套娃」信封(便可以把一個信封放到另外一個信封裏面)。ide
說明:
不容許旋轉信封。spa
示例:code
輸入: envelopes = 輸出: 3 解釋: 最多信封的個數爲 [2,3] => [5,4] => [6,7]。[[5,4],[6,4],[6,7],[2,3]]3, 組合爲:
356ms
1 class Solution { 2 //二分法 3 func maxEnvelopes(_ envelopes: [[Int]]) -> Int { 4 var envelopes = envelopes 5 var dp:[Int] = [Int]() 6 envelopes.sort(by:sortArray) 7 for i in 0..<envelopes.count 8 { 9 var left:Int = 0 10 var right:Int = dp.count 11 var t:Int = envelopes[i][1] 12 while(left < right) 13 { 14 var mid:Int = left + (right - left) / 2 15 if dp[mid] < t 16 { 17 left = mid + 1 18 } 19 else 20 { 21 right = mid 22 } 23 } 24 if right >= dp.count 25 { 26 dp.append(t) 27 } 28 else 29 { 30 dp[right] = t 31 } 32 } 33 return dp.count 34 } 35 36 func sortArray(_ a:[Int],_ b:[Int]) -> Bool 37 { 38 if a[0] == b[0] 39 { 40 return a[1] > b[1] 41 } 42 return a[0] < b[0] 43 } 44 }
6948mshtm
1 class Solution { 2 func maxEnvelopes(_ envelopes: [[Int]]) -> Int { 3 if envelopes.count == 0 { return 0 } 4 let sorted = envelopes.sorted { 5 return $0[0] < $1[0] 6 } 7 8 var dp: [Int] = [Int](repeating: 0, count: envelopes.count) 9 var res = 0 10 for i in 0..<sorted.count { 11 dp[i] = 1 12 for j in 0..<i { 13 // if i is bigger than j 14 if sorted[i][0] > sorted[j][0] && sorted[i][1] > sorted[j][1] { 15 dp[i] = max(dp[i], dp[j] + 1) 16 } 17 } 18 res = max(res, dp[i]) 19 } 20 return res 21 } 22 }