递归:不打印字符串的所有排列。缺少逻辑?

时间:2018-09-12 17:50:16

标签: java recursion

不打印所有排列和程序出口。仅打印三个排列可停止递归;给定的字符串为“ ABCD”

    private static void myPermutations( String permutation,
                                    String str )
{
    if( str.length() == 0 )
        System.out.println( " -- >" + permutation );

    for( int i = 0; i < str.length(); i++ )
    {
        permutation = permutation + str.charAt( i );
        str = str.substring( 0, i ) + str.substring( i + 1 );
        myPermutations( permutation, str );
    }

}

但这有效。有什么区别?

private static void printPermutations( String candidate,
                                       String remaining )
{
    if( remaining.length() == 0 )
        System.out.println( "--> " + candidate );

    for( int i = 0; i < remaining.length(); i++ )
    {
        String newcandidate = candidate + remaining.charAt( i );
        String newremaining = remaining.substring( 0, i ) + remaining.substring( i + 1 );
        printPermutations( newcandidate, newremaining );
    }
}

1 个答案:

答案 0 :(得分:0)

在第一个实例中,您正在修改用于控制循环内部循环的变量:

for( int i = 0; i < str.length(); i++ )
{
    ...
    str = str.substring( 0, i ) + str.substring( i + 1 );
    ...
}

str变量处于for循环条件下。还可以在循环内部对其进行修改。