[英]Unexpected recursive behavior in Java
public class Main21 {
static int count=0;
public static void printer(String s, int n, int sz){
if(n>sz-1)
return;
String s1=s+"P";
String s2=s+"A";
String s3=s+"L";
if(s1.length() == sz && s2.length() == sz && s3.length() == sz){
if( !s1.contains("AA") && !s1.contains("LLL") && !s2.contains("AA") && !s2.contains("LLL") && !s3.contains("AA") && !s3.contains("LLL") )
{
System.out.print(s1+" "+s2+" "+s3+" ");
count++;
}
}
printer(s1,n+1,sz);
printer(s2,n+1,sz);
printer(s3,n+1,sz);
}
public static void main(String[] args) {
int sz=2 ;
printer("P",1,sz);
printer("A",1,sz);
printer("L",1,sz);
System.out.println("\n"+count*3);
}
}
I am getting result: PP PA PL LP LA LL 6
我得到结果:
PP PA PL LP LA LL 6
AL and AP is getting missed. AL 和 AP 被遗漏了。 But when I am passing size as 3 its working fine.
但是当我将尺寸传递为 3 时,它工作正常。 Could you please point out the fault?
你能指出错误吗?
When passed 3:通过 3 时:
PPP PPA PPL PLP PLA PLL APP APA APL ALP ALA ALL LPP LPA LPL 15
I think the problem is that when you check the strings you skip printing all of them even if only one of the three is invalid.我认为问题在于,当您检查字符串时,即使这三个字符串中只有一个无效,您也会跳过打印所有字符串。
Here's possible solution that also removes some duplicated code:这是可能的解决方案,它也删除了一些重复的代码:
public class Main21 {
static int count = 0;
public static void printer(String s, int n, int sz) {
if ( n > sz - 1 ) {
return;
}
String s1 = s + "P";
String s2 = s + "A";
String s3 = s + "L";
StringBuilder builder = new StringBuilder();
appendIfValid( builder, sz, s1, s2, s3 );
if ( builder.length() > 1 ) {
System.out.print( builder.toString() );
count++;
}
printer( s1, n + 1, sz );
printer( s2, n + 1, sz );
printer( s3, n + 1, sz );
}
private static void appendIfValid(StringBuilder builder, int sz, String... strings) {
for ( String s : strings ) {
if ( valid( sz, s ) ) {
builder.append( s );
builder.append( " " );
}
}
}
private static boolean valid(int sz, String s) {
return s.length() == sz
&& !s.contains( "AA" )
&& !s.contains( "LLL" );
}
public static void main(String[] args) {
int sz = 3;
printer( "P", 1, sz );
printer( "A", 1, sz );
printer( "L", 1, sz );
System.out.println( "\n" + count * 3 );
}
}
This code could be improved by skipping the recursion when the string is invalid.当字符串无效时,可以通过跳过递归来改进此代码。 You could also create the
StringBuilder
only once and print everything once at the end.您也可以只创建一次
StringBuilder
并在最后打印所有内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.