这是Java,但是你可以认为这是伪代码:
public static boolean nextPermutation (int [] permutation)
{
int l = permutation.length;
if (l < 2) return false;
else
{
int i = l - 1;
while (i >= 0 && permutation [i] == 0)
i--;
int j = 0;
while (i >= 0 && permutation [i] == 1)
{
i--;
j++;
}
if (i < 0) return false;
else
{
permutation [i] = 1;
Arrays.fill (permutation, i + 1, l - j + 1, 0);
Arrays.fill (permutation, l - j + 1, l, 1);
return true;
}
}
}
public static void main(String[] args) {
int [] permutation = new int [] {0, 0, 0, 1, 1, 1, 1};
do
{
for (int i: permutation)
System.out.print(i);
System.out.println();
} while (nextPermutation(permutation));
}
输出对我来说是:
0001111
0010111
0011011
0011101
0011110
0100111
0101011
0101101
0101110
0110011
0110101
0110110
0111001
0111010
0111100
1000111
1001011
1001101
1001110
1010011
1010101
1010110
1011001
1011010
1011100
1100011
1100101
1100110
1101001
1101010
1101100
1110001
1110010
1110100
1111000
如何从'0011'得到'1001'年初D.E.Knuth
见算法L(字典排列代)? – 2013-03-02 08:41:27
@ n.m。我的算法将从'0011'变为'0101'。你为什么要从'0011'去'1001'? – 2013-03-02 14:36:53
我不希望它直接从'0011'到'1001',我希望它最终到达那里。它会永远吗? – 2013-03-02 14:46:29