递归调用后的代码

ben*_*000 2 java recursion logic

为什么递归后调用System.out.println(res)仍然运行?我以为它永远不会到达System.out.println(res);

public class recursion
{
    public static void main(String[] args)
    {
        recursion p = new recursion();
        p.perms(4, "");
    }

    public void perms(int remaining, String res)
    {
        if (remaining > 0) {
           perms(remaining - 1, res + "1");
            System.out.println(res);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

sti*_*ike 7

想一想这些步骤

call perms(4,"");                   //1 st rec
        perms(3,"1");               //2 nd rec
           perms(2,"11");           //3 rd rec
              perms(1,"111');       //4 th rec
Run Code Online (Sandbox Code Playgroud)

然后因为remaining = 0它不会去,如果是这样现在考虑相反的顺序

           go back to 4th rec and print 111
        go back to 3rd rec and print 11
      go back to 2nd rec and pring 1
    go back to 1st rec and print (blank space)
Run Code Online (Sandbox Code Playgroud)