9ms C++ iterative solution without extra space


  • 0
    N
    class Solution {
    public:
        vector<vector<int>> permute(vector<int>& nums) {
             vector<vector<int> > ans;
             ans.push_back(nums);
             for(int i = 0;i < nums.size();++i){
                 int size = ans.size();
                 for(int j = 0;j < size;++j){
                     for(int k = i + 1;k < nums.size();++k){
                         vector<int> vec = ans[j];
                         swap(vec[i], vec[k]);
                         ans.push_back(vec);
                     }
                 }
             }
             return ans;
        }
    };
    

Log in to reply
 

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