Java递归输出与预期不同

时间:2017-03-22 22:09:44

标签: java

当我以为我开始理解递归时,当n为1但n为2时,这个似乎很简单在我的脑海里,我最终得到了[[,[,[,]

public void ps (int n){

  if (n==0) {
    System.out.print ("*");  
  }
  else {
    System.out.print ("[");
    ps (n-1);
    System.out.print (",");
    ps (n-1);
    System.out.print ("]");
  }
}

2 个答案:

答案 0 :(得分:0)

  ps(2):
     Current output ""
     n != 0 so else: print [ output = "[" 
     call ps(1)
     ps(1):
       Current output "["
       n != 0 so else: print [ output = "[[" 
       call ps(0)
       ps(0):
        Current output "[["
         n == 0: print "*" output = "[[*"
         return
     ps (1): after first call
       output = "[[*"
       print "," output = "[[*,"
       call ps(0):
       ps(0):
         current output "[[*,"
         n == 0: print "*" output = "[[*,*"
         return
    ps(1): after second call
       output = "[[*,*"
       print "]" output = "[[*,*]"
       return
  ps(2): after first call
    output = "[[*,*]"
    print , output = "[[*,*],"
    call ps(1)
             ps(1):
       Current output [[*,*],
       n != 0 so else: print [ output = "[[*,*],[" 
       call ps(0)
       ps(0):
        Current output "[[*,*],[" 
         n == 0: print "*" output = "[[*,*],[*"
         return
     ps (1): after first call
       output = "[[*,*],[*"
       print "," output = "[[*,*],[*,"
       call ps(0):
       ps(0):
         current output "[[*,*],[*,"
         n == 0: print "*" output = "[[*,*],[*,*"
         return
    ps(1): after second call
       output = "[[*,*],[*,*"
       print "]" output = "[[*,*],[*,*]"
       return
   ps(2): after second call
       output = "[[*,*],[*,*]"
       print "]" output = "[[*,*],[*,*]]"
       return

最终输出:"[[*,*],[*,*]]"

答案 1 :(得分:0)

好吧,您可能已经听过stack framecall stack这两个词。它们对于理解递归中发生的事情非常重要。

我的建议是根据他们的调用在树中绘制stack frames

在这种情况下,它看起来像:

ps(2)
  |
  |--ps(1)
  |    |
  |    |--ps(0)
  |
  |--ps(1)
  |    |
  |    |--ps(0)

现在添加每个调用的输出,你应该没问题。

  • 如上所述,未来的问题会尝试解释您的期望或您想要实现的目标。