C++ iterative solution


  • 1
    B
    ////////////////Leetcode passed, iterative ///////////////////////////
    /**            [  1 , 2  ]
                     ^  ^  ^
    insert 3:        |  |  |    there are 3 positions to insert
    
    **/
    vector<vector<int>> permute(vector<int>& nums) {
        vector<vector<int>> result;
        vector<vector<int>> buffer;
        result.push_back(vector<int>());
    
        for(int i=0; i<nums.size(); ++i){
            int vec_n = result.size();
            for(int j=0; j<vec_n; ++j){
                int vec_size = result[j].size();
                for(int k=0; k<=vec_size; ++k){
                    vector<int> tmp(result[j]);
                    tmp.insert(tmp.begin()+k, nums[i]);
                    buffer.push_back(tmp);
                }
            }
            result=buffer;
            buffer.clear();
        }
    
        return result;
    }

Log in to reply
 

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