這是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