[leetcode_46]Permutations

Generate all permutations of the input array and output them.

I kept getting Output Limit Exceeded and couldn’t figure out why.

I remembered asking a friend about it, and he said my output was larger than expected. The judge gave OLE after checking.

That felt even worse than getting TLE – at least with TLE I could optimize my code!

Later I wondered if there were duplicate elements in the array. I tried checking for duplicates before inserting into the vector, but still got OLE.

Finally I gave up and looked at other people’s solutions. The approach was the same as mine.

Then I suddenly noticed there’s a problem called Permutations II, which says the data may contain duplicates – meaning this problem’s data should NOT have duplicates!

Looking more carefully at others’ code, I noticed something more professional: vector.clear().

Just that one line was missing.

After adding it – Accepted!

Here is the code (a bit rough):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution {
public:
    vector<vector<int>> ans;
    bool flag[100000];
    int sum;
    vector<vector<int>> permute(vector<int> &num) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        sum = num.size();
        ans.clear();
        for(int i = 0;i < sum;i++) {
            flag[i] = false;
        }
        for(int i = 0;i < sum;i++) {
            flag[i] = true;
            vector<int> tmp(sum);
            tmp[0] = i;
            fun(tmp,1,num);
            flag[i] = false;
        }
        return ans;
    }
    void fun(vector<int> &tmp,int k,vector<int> &num) {
        if(k >= sum) {
            vector<int> numtmp(sum);
            for(int i = 0;i < sum;i++) {
                numtmp[i] = num[tmp[i]];
            }
            ans.push_back(numtmp);
            return ;
        }
        for(int i = 0;i < sum;i++) {
            if(!flag[i]) {
                flag[i] = true;
                tmp[k] = i;
                fun(tmp,k+1,num);
                flag[i] = false;
            }
        }
    }
};