2017-03-22 10 views
-3

ちょうど私が再帰を理解し始めていると思っていたとき、nが1のときにnが2のときシンプルなように見えますが、nが2のとき頭では[[、[、[]Java recursionの出力が期待と異なる

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 ("]"); 
    } 
} 
+5

よくやっていると思いますが、それは何ですか?それから始めよう。 – twain249

+0

あなたのメソッドの@Jason署名は、 'Public void ps(int n)'ではなく 'public void ps(int number)'のようになります。 –

+0

申し訳ありませんが、タイプoがプログラムにないと入力しました – Jason

答えて

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 

最終的な出力:"[[*,*],[*,*]]"

+0

ご協力いただきありがとうございます。 – Jason

0

さて、あなたはおそらくすでに用語stack framecall stackを聞きました。再帰で何が起こるのかを理解することは非常に重要です。

私のヒントは、その呼び出しに応じてstack framesをツリーに描くことです。今、それぞれの呼び出しからこれに出力を追加し、あなたは問題ないはず

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

この場合、それは次のようになります。

  • 前述したように、将来の質問では、あなたが何を期待しているのか、あるいは何を達成しようとしているのかを説明してください。
+0

コールスタックはいスタックフレームいいえバックアップのようなものです – Jason

+0

ここを見てくださいhttp://stackoverflow.com/questions/10057443/explain-the-concept-of-a- stack-frame-in-a-nutshell - 基本的に、funtionの呼び出しに渡される情報です。最も興味深い部分はパラメータですが、リターンアドレスのようなものも含まれます(実行時に実行されるコード)と返り値を入れる場所(voidでない場合)などがあります。最後の2つは通常は当然のことですが、再帰を学習するときには役に立ちます。 –

関連する問題