boolnext_permu(int start, int end){ if (end < start) returnfalse; // find the longest increase sub str from the end int ptr1; for (ptr1 = end - 1; ptr1 >= start; --ptr1){ if (li[ptr1] < li[ptr1 + 1])break; } if (ptr1 < start) returnfalse;
// find the first one which is larger than li[ptr] from the end // it is guaranteed that this ptr2 will be found int ptr2; for (ptr2 = end; ptr2 > ptr1; --ptr2){ if (li[ptr2] > li[ptr1])break; }
// swap the numbers pointed by ptr1 and ptr2 int temp = li[ptr1]; li[ptr1] = li[ptr2]; li[ptr2] = temp;
// reverse the string from ptr1 + 1 to end for (int i = ptr1 + 1, j = end; i < j; ++i, --j){ temp = li[i]; li[i] = li[j]; li[j] = temp; } returntrue; }
// the recursive solution voidpermu(int num){ if (num == 1){ for (int i = 0; i < N; ++i){ cout << li[i] << " "; } cout << endl; return; } for (int i = N - num; i < N; ++i){ swap(li[N - num], li[i]); permu(num - 1); swap(li[N - num], li[i]); } }
intmain(int argc, constchar * argv[]){ for (int i = 1; i <= N; ++i){ li[i - 1] = i; } do{ for (int i = 0; i < N; ++i){ cout << li[i] << " "; } cout << endl; } while (next_permu(0, N - 1));