Skip to content

Latest commit

 

History

History
65 lines (54 loc) · 1.45 KB

16.md

File metadata and controls

65 lines (54 loc) · 1.45 KB

PERMUTATION

Practice

METHOD

void find(int ind,vector<vector<int>> &ans,vector<int>&nums){

        if(ind>=nums.size())
        {
            ans.push_back(nums);
            //s.insert(nums);
            return;
        }

        for(int i=ind;i<nums.size();i++)
        {
            swap(nums[ind],nums[i]);
            find(ind+1,ans,nums);
            swap(nums[ind],nums[i]);
        }
    }
    vector<vector<int>> permute(vector<int>& nums) {
        vector<vector<int>> ans;
      
        find(0,ans,nums);
        return ans;
    }

METHOD 2(TLE)

  void find(vector<vector<int>>&ans,vector<int>&temp,vector<int>v,int n,vector<int>arr)
    {
        if(temp.size()==n && std::find(ans.begin(),ans.end(),temp)==ans.end())
        {
            ans.push_back(temp);
            return;
        }
        for(int i=0;i<n;i++)
        {
            if(v[i]!=1)
            {
                    v[i]=1;
                temp.push_back(arr[i]);
                find(ans,temp,v,n,arr);
            
                temp.pop_back();
                v[i]=0;
            }
        }
    }
    vector<vector<int>> uniquePerms(vector<int> &arr ,int n) {
        // code here
        vector<int>v(n,0);
        sort(arr.begin(),arr.end());
        
        vector<vector<int>>ans;
        vector<int>temp;
        
        find(ans,temp,v,n,arr);
        return ans;
    }