Created
November 2, 2018 08:31
-
-
Save ms1797/eeafb02972fc42bc1c7f38910889dd4b to your computer and use it in GitHub Desktop.
Given a collection of numbers(unique elements), return all possible permutations. (https://www.interviewbit.com/problems/permutations/)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Given a collection of numbers, return all possible permutations. | |
Example: | |
[1,2,3] will have the following permutations: | |
[1,2,3] | |
[1,3,2] | |
[2,1,3] | |
[2,3,1] | |
[3,1,2] | |
[3,2,1] | |
NOTE:: | |
No two entries in the permutation sequence should be the same. | |
For the purpose of this problem, assume that all the numbers in the collection are unique. | |
Approach :: | |
Lets say we are at index start then we can swap element at this index with any index>start and permute | |
the elements starting from start+1 using recursion. You can swap back the elements at start and index | |
in order to maintain the order for next recursive call. | |
*/ | |
#include<bits/stdc++.h> | |
using namespace std; | |
void display_vector(vector<int> &arr ) | |
{ | |
for(int i = 0 ; i<arr.size() ; i++) | |
{ | |
cout<<arr[i]<<" " ; | |
} | |
cout<<"\n" ; | |
} | |
void display_vectorOfVector(vector<vector<int> > &arr ) | |
{ | |
for(int i = 0 ; i<arr.size() ; i++) | |
{ | |
for(int j = 0 ; j<arr[i].size() ; j++) | |
cout<<arr[i][j]<<" " ; | |
cout<<"\n" ; | |
} | |
} | |
void permute_helper(vector<vector<int> > &res , vector<int> &A , int start) | |
{ | |
//base case | |
if(start == A.size()-1) | |
{ | |
res.push_back(A) ; | |
return ; | |
} | |
//recursive case | |
for(int i = start ; i<A.size(); i++) | |
{ | |
swap(A[i] , A[start]) ; | |
permute_helper(res, A , start+1 ) ; | |
swap(A[i] , A[start]) ; | |
} | |
} | |
vector<vector<int> > permute(vector<int> &A) { | |
vector<vector<int> > res ; | |
permute_helper(res , A , 0 ) ; | |
return res ; | |
} | |
int main() | |
{ | |
vector<int> A ; | |
int n ; | |
cout<<"enter the number of elements :" ; | |
cin>>n ; | |
cout<<endl ; | |
for(int i = 0 ; i < n ; i++) | |
{ | |
int temp ; | |
cout<<"enter element :" ; | |
cin>>temp ; | |
A.push_back(temp) ; | |
cout<<endl ; | |
} | |
vector< vector<int> > ans = permute(A) ; | |
cout<<"Output of program ==>\n" ; | |
display_vectorOfVector(ans) ; | |
return 0 ; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment