Why get Memory Limit Exceeded after submitting this code?


  • 0
    X

    If I write the code like this, I would get Memory Limit Exceeded:

    class Solution {
    public:
        vector<vector<int> > subsets(vector<int> &S) {
            sort(S.begin(), S.end());
            vector<vector<int> > result(1);
            for (int i = 0; i < S.size(); ++i) {
                for (int j = 0; j < result.size(); ++j) {
                //for (int j = result.size() - 1; j >= 0; --j) {
                    result.push_back(result[j]);
                    result.back().push_back(S[i]);
                }
            }
            return result;
        }
    };
    

    If I use the commented line instead, it would be accepted. Why? BTW, I believe that it does work if we start from the first subset and add current element to it and put it into the result until the end.


  • 4
    S

    Here's the problem. MLE sometimes means TLE, as your code hit the memory limit first when you are in endless loop.

    Your result size is always growing in j-loop. Everytime, you meet the for-condition will re-count the result size, it will lead to dead loop. But, in the comment way, from size to 0, it only counts once at the very beginning. So this will get accepted.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.