2016-11-27 82 views
0

這個想法是,如果我在某個樓梯我可以走一步或兩步,所以如果我在樓梯3我可以走下去1 1 1或2 1例如。我的代碼應該打印所有的可能性。我得到的錯誤是我無法將add函數轉換爲數組(因爲add方法是一個布爾值)。這個算法有什麼問題?在遞歸算法中使用數組來尋找組合

public class Stairs { 

public static void staircase (int height ){ 

    ArrayList<Integer> Array = null; 
    explore (height,Array); 
} 
public static void explore(int objheight,ArrayList<Integer>Array){ 
    int intialheight = 0; 
    if (intialheight == objheight){ 
     Array.toString(); 
    } 
    else{ if (objheight > intialheight){ 
     explore(objheight-2,Array.add(2)); 
     explore(objheight-1,Array.add(1)); 
    } 
} 
您的意見我得到一個空的輸出 進口java.lang.reflect.Array中後

; import java.util.ArrayList;

public class Stairs { 

public static void staircase (int height ){ 

    ArrayList<Integer> Array = new ArrayList<Integer>(); 
    explore (height,Array); 
} 
public static void explore(int objheight,ArrayList<Integer>Array){ 
    int intialheight = 0; 
    if (intialheight == objheight){ 
     Array.toString(); 
    } 
    else{ if (objheight > intialheight){ 
     Array.add(2); 
     explore(objheight-2,Array); 
     Array.add(1); 
     explore(objheight-1,Array); 
    } 
}} 
public static void main (String args[]){ 
staircase(3); 

    } 
} 
+0

什麼是 「add函數轉換爲數組」 是什麼意思?我很肯定你會得到一個NullPointerException。 – Henry

回答

1

方法add(E e)在ArrayList中追加時作爲參數到ArrayList的端部傳遞的元素e返回true

您的方法explore(int objHeight, ArrayList<Integer> Array)不接受其第二個參數的布爾值。然而,在同樣的方法中,explore,你遞歸調用explore並傳入一個布爾值給方法。

應修改以下代碼,以首先調用Arrayadd方法,然後將Array傳遞給explore方法。

之前:

explore(objheight-2,Array.add(2));該代碼被傳遞參數intbooleanexplore方法,這不是它接受的參數。您應該嘗試以下操作。

後:

Array.add(2); explore(objheight-2,Array);此代碼首先增加了2至Array和隨後將Arrayexplore方法而不調用Array對象上的任何其它方法。


您還需要爲代碼的下一行,在那裏你有explore(objheight-1,Array.add(1));做到這一點。


編輯:在進一步檢查代碼後,我發現了另一個(更快)的錯誤。產生NullPointerException每個程序運行時間將發生:

ArrayList<Integer> Array = null; explore (height,Array);

然後explore方法內,上Array不同的方法被調用時,儘管Array始終是null

Array.toString();Array.add(2)Array.add(1)

Array對象必須在staircaseexplore方法中進行初始化。

ArrayList<Integer> Array = new ArrayList<Integer>();ArrayList<Integer> Array = null; Array = new ArrayList<Integer>();