← Home

354. Russian Doll Envelopes

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
dynamic programmingC++Markdown
354

Let's make this one less mysterious. For 354. Russian Doll Envelopes, the solution in this repository is mainly a dynamic programming solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: dynamic programming, binary search.

The notes already sitting in the source point us in the right direction:

  • LIS
  • time: O(N^2), space: O(N)

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are maxEnvelopes.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(NlogN), space: O(N)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//LIS
02//Runtime: 1360 ms, faster than 17.56% of C++ online submissions for Russian Doll Envelopes.
03//Memory Usage: 16.5 MB, less than 16.67% of C++ online submissions for Russian Doll Envelopes.
04//time: O(N^2), space: O(N)
05class Solution {
06public:
07    int maxEnvelopes(vector<vector<int>>& envelopes) {
08        int n = envelopes.size();
09        if(n == 0) return 0;
10        
11        vector<int> dp(n, 1);
12        int ans = 1;
13
14        //the envelopes with smaller width/height are put before
15        sort(envelopes.begin(), envelopes.end());
16        
17        //LIS
18        for(int j = 1; j < n; j++){
19            for(int i = 0; i < j; i++){
20                //stricter condition than ordinal LIS
21                if(envelopes[i][0] < envelopes[j][0] && envelopes[i][1] < envelopes[j][1]){
22                    dp[j] = max(dp[j], dp[i]+1);
23                }
24            }
25            ans = max(ans, dp[j]);
26        }
27
28        return ans;
29    }
30};
31
32//LIS, binary search
33//https://leetcode.com/problems/russian-doll-envelopes/discuss/82763/Java-NLogN-Solution-with-Explanation
34//Runtime: 92 ms, faster than 77.75% of C++ online submissions for Russian Doll Envelopes.
35//Memory Usage: 16.4 MB, less than 16.67% of C++ online submissions for Russian Doll Envelopes.
36//time: O(NlogN), space: O(N)
37class Solution {
38public:
39    int maxEnvelopes(vector<vector<int>>& envelopes) {
40        int n = envelopes.size();
41        if(n == 0) return 0;
42        
43        vector<vector<int>> top;
44
45        /*
46        since we don't want [3,4] be put into [3,5],
47        we won't want [3,4] to be put before [3,5],
48        so we sort the sequence ascending by width and "DESCENDING" by height
49        */
50        sort(envelopes.begin(), envelopes.end(),
51            [](const vector<int>& v1, const vector<int>& v2){
52                return (v1[0] == v2[0]) ? (v1[1] > v2[1]) : (v1[0] < v2[0]);
53            });
54        
55        // for(vector<int>& p : envelopes){
56        //     cout << "(" << p[0] << ", " << p[1] << ") -> ";
57        // }
58        // cout << endl;
59        
60        for(vector<int>& p : envelopes){
61            int lo = 0, hi = top.size()-1;
62            
63            /*
64            want to find lo s.t. top[lo] is just larger than p
65            */
66            while(lo <= hi){
67                int mid = lo + (hi-lo)/2;
68                
69                //this is wrong!
70                // if(p[0] < top[mid][0] && p[1] < top[mid][1]){
71                /*
72                we only need to compare their heights,
73                since their widths are already sorted
74                */
75                if(top[mid][1] > p[1]){
76                    hi = mid-1;
77                }else if(top[mid][1] == p[1]){
78                    //since we want to find lower bound
79                    hi = mid-1;
80                }else if(top[mid][1] < p[1]){
81                    lo = mid+1;
82                }
83            }
84            
85            if(lo == top.size()){
86                top.push_back(p);
87                // cout << "push [" << p[0] << ", " << p[1] << "]" << endl;
88            }else{
89                top[lo] = p;
90                // cout << "reset top[" << lo << "] to " << "[" << p[0] << ", " << p[1] << "]" << endl;
91            }
92        }
93
94        return top.size();
95    }
96};

Cost

Complexity

Time
O(NlogN), space: O(N)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.