不打印所有排列和程序出口。仅打印三个排列可停止递归;给定的字符串为“ 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 );
}
}
答案 0 :(得分:0)
在第一个实例中,您正在修改用于控制循环内部循环的变量:
for( int i = 0; i < str.length(); i++ )
{
...
str = str.substring( 0, i ) + str.substring( i + 1 );
...
}
str变量处于for循环条件下。还可以在循环内部对其进行修改。