Share my C++ recursive solution,easy to understand


  • 1
    V
    class Solution {
    public:
        vector<vector<int>> permute(vector<int>& nums) {
            vector<vector<int>> ret;
            int n = nums.size();
            if (n == 0)
                return ret;
            
            if (n == 1)
            {
                ret.push_back(nums);
                return ret;
            }
            
            int i = 0, j = 0, len = 0;
            vector<int> curNums;
            vector<int> per;
            vector<vector<int>> temp;
            
            for (i = 0; i < n; i++)
            {
                curNums = nums;
                curNums.erase(curNums.begin()+i);
                temp = permute(curNums);
                len = temp.size();
                
                for (j = 0; j < len; j++)
                {
                    per = temp[j];
                    per.push_back(nums[i]);
                    ret.push_back(per);
                }
            }
                
            return ret;
        }
        
    };

Log in to reply
 

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