这是在 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