跟踪递归

时间:2016-01-09 00:26:31

标签: java recursion

我在网上看到了这个代码,我想跟踪递归。我设法这样做了:

A 
AB
ABC

我认为我做错了。

这是代码:

public class Test
{
    public static void main(String[] args)  
    {
        printAll("ABC", 0, new StringBuffer());
        //      Outputs
        //      ---------
        //      A
        //      AB
        //      ABC
        //      AC
        //      B
        //      BC    
        //      C
    }

    private static void printAll(String str,int start, StringBuffer sb)
    {
        for(int i=start; i< str.length(); i++)
        {
            sb.append(str.charAt(i));
            System.out.println(sb);
            printAll(str, i+1, sb);
            sb.setLength(sb.length()-1);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

这是一个简单的问题,即展开&#39;:

输入序列为ABC,因此:

for(int i=start; i< str.length(); i++)
{
    sb.append(str.charAt(i));
    System.out.println(sb);
    printAll(str, i+1, sb);
    sb.setLength(sb.length()-1);
}

展开,start设置为0:

sb.append("ABC".charAt(0));
System.out.println(sb);
printAll("ABC", 1, sb); //Recursive call
sb.setLength(sb.length()-1);
sb.append("ABC".charAt(1));
System.out.println(sb);
printAll("ABC", 2, sb); //Recursive call
sb.setLength(sb.length()-1);
sb.append("ABC".charAt(2));
System.out.println(sb);
printAll("ABC", 3, sb); //Recursive call
sb.setLength(sb.length()-1);

鉴于长度为3,我们就在那里结束。但现在我们还需要展开递归调用:

sb.append("ABC".charAt(0)); // sb="A"
System.out.println(sb);
//Entering recursive call, start=1
    sb.append("ABC".charAt(1));  // sb="AB"
    System.out.println(sb);

    //Entering recursive call, start=2
        sb.append("ABC".charAt(2));  // sb="ABC"
        System.out.println(sb);
        //Enter recursive call, start=3
            // 3 is not less than "ABC".length(), so we leave immediately
        //Exit recursive call
        sb.setLength(sb.length()-1);  // sb="AB"
    //Exit recursive call

    sb.setLength(sb.length()-1);  // sb="A"
    sb.append("ABC".charAt(2));  // sb="AC"
    System.out.println(sb);
    //Enter recursive call, start=3
        // 3 is not less than "ABC".length(), so we leave immediately
    //Exit recursive call
    sb.setLength(sb.length()-1);  // sb="A"
//Exit recursive call

sb.setLength(sb.length()-1);  // sb=""
sb.append("ABC".charAt(1));  // sb="B"
System.out.println(sb);

//Entering recursive call, start=2
    sb.append("ABC".charAt(2));  // sb="BC"
    System.out.println(sb);
    //Enter recursive call, start=3
        // 3 is not less than "ABC".length(), so we leave immediately
    //Exit recursive call
    sb.setLength(sb.length()-1);  // sb="B"
//Exit recursive call

sb.setLength(sb.length()-1);  // sb=""
sb.append("ABC".charAt(2));  // sb="C"
System.out.println(sb);

//Enter recursive call, start=3
    // 3 is not less than "ABC".length(), so we leave immediately
//Exit recursive call

sb.setLength(sb.length()-1);  // sb=""

完全展开&#39;我们可以将其粘贴到main函数中并执行它,看到预期的结果。您还可以在评论中查看代码在每个步骤中执行的操作。