2015-04-04 99 views
-1

我的書有一個類似於this的程序。需要解釋Java程序邏輯

public class Partition { 

public static void partition(int n) { 
    partition(n, n, ""); 
} 
public static void partition(int n, int max, String prefix) { 
    if (n == 0) { 
     StdOut.println(prefix); 
     return; 
    } 

    for (int i = Math.min(max, n); i >= 1; i--) { 
     partition(n-i, i, prefix + " " + i); 
    } 
} 


public static void main(String[] args) { 
    int N = Integer.parseInt(args[0]); 
    partition(N); 
} 

} 

是否有另一種方式來寫循環以不同的方式,這對我來說不是那麼複雜?謝謝!

+1

你覺得一個方法調用'Math.min'呢?你讀過javadoc嗎? – 2015-04-04 23:41:17

+0

你讓自己被未知的人嚇倒。但是你「知道」這個方法可能做什麼,如果沒有,你一定能夠找到答案,用它所執行的代碼交換單個調用並不會讓我更容易理解,我不這麼認爲。 – ChiefTwoPencils 2015-04-04 23:44:30

+1

看看[文檔](http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#min%28int,%20int%29)。 – 2015-04-04 23:46:41

回答

0

當試圖理解遞歸方法/函數時,我發現添加一些明智的調試代碼會很有幫助,這些代碼可以告訴您每個步驟中發生了什麼。爲了增加視覺吸引力,我添加了一個debugIndent,它直觀地告訴我我在哪個級別。

StdOut(debugIndent + "n = " + n + ", max = " + max + ", prefix = \"" prefix + "\""); 

把,在你的第二個分區的開始,像這樣:

Public class Partition { 

    public static void partition(int n) { 
     partition("", n, n, ""); 
    } 
    public static void partition(String debugIndent, int n, int max, String prefix) { 
     StdOut(debugIndent + "n = " + n + ", max = " + max + ", prefix = \"" prefix + "\""); // TODO remove debugging code 

     if (n == 0) { 
      StdOut.println(prefix); 
      return; 
     } 

     for (int i = Math.min(max, n); i >= 1; i--) { 
      partition(debugIndent + " ", n-i, i, prefix + " " + i); 
     } 
    } 


    public static void main(String[] args) { 
     int N = Integer.parseInt(args[0]); 
     partition(N); 
    } 
} 

運行,看看它顯示你。