Permutations II in C++

C++Server Side ProgrammingProgramming

Suppose we have a collection of distinct integers; we have to find all possible permutations. Now if the array stores the duplicate elements, then ignore that state which is looking similar. So if the array is like [1,1,3], then the result will be [[1,1,3], [1,3,1], [3,1,1]]

To solve this, we will follow these steps −

  • We will use the recursive approach, this will make the list, index. Index is initially 0
  • if index = size of the list then insert list into res array, and return
  • for i in range index to length of given list – 1
    • if list[i] = list[index] and i is not same as index, then continue without looking the next step
    • swap the elements of list present at index start and i
    • permutation(list, start + 1)
  • initially call the permutation(list), and return res

Example(C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<int> > v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << "[";
      for(int j = 0; j <v[i].size(); j++){
         cout << v[i][j] << ", ";
      }
      cout << "],";
   }
   cout << "]"<<endl;
}
class Solution {
public:
   vector < vector <int> > res;
   void solve(vector <int> nums, int idx = 0){
      if(idx == nums.size()){
         res.push_back(nums);
         return;
      }
      for(int i = idx; i <nums.size(); i++){
         if(nums[i] == nums[idx] && i != idx)continue;
         swap(nums[i], nums[idx]);
         solve(nums, idx + 1);
      }
   }
   vector<vector<int>> permuteUnique(vector<int>& nums) {
      res.clear();
      sort(nums.begin(), nums.end());
      solve(nums);
      return res;
   }
};
main(){
   Solution ob;
   vector<int> v = {1,1,3};
   print_vector(ob.permuteUnique(v));
}

Input

[1,1,3]

Output

[[1,1,3],[1,3,1],[3,1,1]]
raja
Published on 31-Jan-2020 10:24:41
Advertisements