Created
February 10, 2012 21:15
-
-
Save aruslan/1792938 to your computer and use it in GitHub Desktop.
Generate all unique permutations?
This file contains 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
#include <vector> | |
#include <algorithm> | |
#include <iostream> | |
#include <ostream> | |
#include <iterator> | |
template<typename T> | |
void print(const std::vector<T>& v) | |
{ | |
std::copy(v.begin(), v.end(), std::ostream_iterator<T>(std::cout)); | |
std::cout << std::endl; | |
} | |
template<typename T> | |
void permute(std::vector<T>& v, int i = 0) | |
{ | |
if (i == (int)v.size()) | |
print(v); | |
else | |
{ | |
T last = T(); | |
for(int j = i, e = v.size(); j< e; ++j) | |
{ | |
if ( j!= i && last == v[j]) | |
continue; | |
last = v[j]; | |
std::swap(v[i], v[j]); | |
permute(v, i+1); | |
std::swap(v[i], v[j]); | |
} | |
} | |
} | |
int main() | |
{ | |
//int arr[] = {1,2,2,3}; | |
//std::vector<int> v(arr, arr+sizeof(arr)/sizeof(arr[0])); | |
char arr[] = "Hello"; | |
std::vector<char> v(arr, arr+sizeof(arr)/sizeof(arr[0])-1); | |
std::sort(v.begin(), v.end()); | |
permute(v); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment