a c++ solution using “erase” method

  • 0


    vector<vector<int>> permute(vector<int>& nums) {
        vector<vector<int>> res;                        
        vector<int> permut;                             // create a variant to record each permutation
        findPermut(nums, permut, res);
        return res;
    /*  recursive method 
        we pick up a number from "nums" each time and push it into a permutation --"permut".
    void findPermut(vector<int>& nums, vector<int>& permut, vector<vector<int>>& res){
        for(int i = 0; i < nums.size(); ++i){
            vector<int> newPermut(permut);
            vector<int> leftNums(nums);
            newPermut.push_back(nums[i]);               // pick up a number and push it into "permut" which is renamed "newPermut".
            leftNums.erase(leftNums.begin()+i);         // since the number has joined the permutation, we can only pick up another number in the "leftNums".
                res.push_back(newPermut);               // if there is no left nums to pick, the permut is complete.
                findPermut(leftNums, newPermut, res);   // otherwise pick up another number from nums.


Log in to reply

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