My 16ms C++ recursive solution without using the provided permutation function or changing the input parameter nums


  • 0
    J
    class Solution {
    public:
        vector<vector<int>> permute(vector<int>& nums) {
            vector<vector<int>> res;
            if (nums.size() > 1)
            {
                int num = nums.back();
                nums.erase(nums.end()-1);
                vector<vector<int>> tmp = permute(nums);
                vector<int> tmpp;
                nums.push_back(num);
                for (int i = 0; i < tmp.size(); i++)
                {
                    for (int j = 0; j <= tmp[i].size(); j++)
                    {
                        tmpp = tmp[i];
                        tmpp.insert(tmpp.begin()+j, num);
                        res.push_back(tmpp);
                    }
                }
            }
            else
                res.push_back(nums);
            return res;
        }
    };

Log in to reply
 

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