Skip to content

Instantly share code, notes, and snippets.

@aruslan
Created February 10, 2012 21:15
Show Gist options
  • Save aruslan/1792938 to your computer and use it in GitHub Desktop.
Save aruslan/1792938 to your computer and use it in GitHub Desktop.
Generate all unique permutations?
#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