Java nextPermutation( )

I like Java. But there is at least one thing missing in Java for sure — permutations.

http://codeforces.com/blog/entry/3980

boolean nextPermutation(int[] p, int st, int ed) {
for (int a = ed - 2; a >= st; a--) {
if (p[a] < p[a + 1]) {
for (int b = ed - 1; ; b--) {
if (p[b] > p[a]) {
int t = p[a];
p[a] = p[b];
p[b] = t;
for (a++, b = ed - 1; a < b; a++, b--) {
t = p[a];
p[a] = p[b];
p[b] = t;
}
return true;
}
}
}
}
return false;
}

 

例:

int[] a = {2, 4, 6, 6, 7};

do {
for (int i = 1; i < 4; i++)
System.out.print(a[i] + " ");
System.out.println();
} while (nextPermutation(a, 1, 4));

结果:

4 6 6
6 4 6
6 6 4

posted on 2013-02-25 21:29  Sure_Yi  阅读(323)  评论(0编辑  收藏  举报

导航