My solution using recursion


  • 0
    V
    class Solution {
    private:
        vector<int> temp;
        vector<vector<int>> result;
    public:
        vector<vector<int>> permute(vector<int>& nums) {
            permute( nums, 0 );
            return result;
        }
    
        void permute( vector<int> &nums, int len ) {
            if( len == nums.size() )
            {
                result.push_back( temp );
                return;
            }
        
        
            for( int i = len; i < nums.size(); i++ )
            {
                std::swap( nums[ len ], nums[ i ] );
                temp.push_back( nums[ len ] );
                permute( nums, len + 1 );
                std::swap( nums[ len ], nums[ i ] );
                temp.pop_back();
            }
        }
    };

Log in to reply
 

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