我正在尝试将以下分区生成器从Python转换为Java,但没有得到预期的结果:
蟒蛇:

def accelAsc(n):
    a = [0 for i in range(n + 1)]
    k = 1
    a[0] = 0
    y = n - 1
    while k != 0:
        x = a[k - 1] + 1
        k -= 1
        while 2*x <= y:
            a[k] = x
            y -= x
            k += 1
        l = k + 1
        while x <= y:
            a[k] = x
            a[l] = y
            yield a[:k + 2]
            x += 1
            y -= 1
        a[k] = x + y
        y = x + y - 1
        yield a[:k + 1]

我的Java:
public static void partition( int n ){
    int[] a = new int[ n + 1 ];
    int k = 1;
    int y = n - 1;
    while( k != 0 ){
        int x = a[k - 1] + 1;
        k -= 1;
        while( 2*x <= y ){
            a[k] = x;
            y -= x;
            k += 1;
        }
        int l = k + 1;
        while( x <= y ){
            a[k] = x;
            a[l] = y;
            for( int xValue = 0; xValue <= k; xValue++ ) System.out.print( a[xValue + 2] );
            System.out.println();
            x += 1;
            y -= 1;
        }
        a[k] = x + y;
        y = x + y - 1;
        for( int xValue = 0; xValue <= k; xValue++ ) System.out.print( a[xValue + 1] );
        System.out.println();
    }
}

使用参数5调用此函数将导致以下打印输出:
1110
1121
132
22
42
2
3

这是不正确的。

最佳答案

凯文的评论引出了答案:
代替

for( int xValue = 0; xValue <= k; xValue++ ) System.out.print( a[xValue + 2] );

具有
for( int xValue = 0; xValue < k + 2; xValue++ ) System.out.print( a[xValue] );


代替
for( int xValue = 0; xValue <= k; xValue++ ) System.out.print( a[xValue + 1] );

具有
for( int xValue = 0; xValue < k + 1; xValue++ ) System.out.print( a[xValue] );

08-19 08:31