Skip to content

Instantly share code, notes, and snippets.

@BaiGang
Created November 5, 2012 02:36
Show Gist options
  • Save BaiGang/4014988 to your computer and use it in GitHub Desktop.
Save BaiGang/4014988 to your computer and use it in GitHub Desktop.
Generate all permutations
#include <iostream>
using namespace std;
void swap(int* a, int* b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
void Perm(int m, int n, int* A) {
if (m == n) {
for (int i = 0; i < n; ++i) {
cout << A[i];
}
cout << "\n";
return;
}
for (int j = m; j < n; ++j) {
swap(&A[m], &A[j]);
Perm(m+1, n, A);
swap(&A[m], &A[j]);
}
}
int main(int argc, char* argv[]) {
int n;
cin >> n;
int * A = new int [n];
for (int i = 0; i < n; ++i) {
A[i] = i + 1;
}
Perm(0, n, A);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment