2014-10-31 60 views
0

我想創建一個遞歸函數,允許我「模擬」一個double for循環。同樣的事情也給用兩個增量遞歸

迭代:

for(int i = 0; i < list.length; i++) { 
     for(int x = i; x < list.length; x++) { 
      //handle logic here 
     } 
    } 

遞歸:

public int solve(int start_index, int end_index) { 

     if(start_index >= array.length) { return 0; } 
     if(end_index >= array.length - 1) { solve(start_index + 1, 0); return 0; } 

     return solve(start_index, end_index + 1); 
} 

但它似乎並沒有我想應該返回類似的結果。誰能幫我嗎?欣賞它!

+2

嗯,你看到的結果,而你能指望什麼看的? (順便說一句,如果你使用了更多的換行符,你的代碼會更清晰,尤其是對於多語句塊)。 – 2014-10-31 18:47:26

+0

你的第二個代碼塊似乎缺少一個'}'。這是你的實際代碼嗎? – Kevin 2014-10-31 18:48:26

+0

@Kevin更新。我想我有點想念它。 – 2014-10-31 18:56:45

回答

0

可以說你的操作是一個整數數組的總和。這是迭代版本:

for (int i = 0; i < array.length; i++) 
    for (int x = i; x < array.length; x++) 
    sum1 += array[x]; 

遞歸版本是這樣的:

public int solve(int x, int i, int end) 
{ 
    if(i == end) 
    return array[x]; 
    else if(x == end) 
    return array[x] + solve(i + 1, i + 1, end); 
    else 
    return array[x] + solve(x + 1, i, end); 
} 

我們呼籲它sum2 = solve(0, 0, array.length-1);

變量ix的語義上都相同版本更好的理解。

最後sum1將與sum2相同。

0

這應該工作(注意我模擬類似的行爲):

public class temp { 

     // This will be the method to simulate the double for loop you had 
     // listed in your question. 
     static void iterate(int index, int sub_index, int end_index) { 

       if (index < end_index){ 
         if (sub_index < end_index){ 
           System.out.println(index + " " + sub_index); 
           iterate(index, sub_index + 1 , end_index); 

         }else { 
           iterate(index + 1, index+1 , end_index) ; 
         } 
       } 
     } 



     public static void main(String[] args){ 
       // Simulate the usual double for loop 
       System.out.println("Double for loop"); 
       for (int i = 0 ; i < 3 ; i++){ 
         for (int j = i ; j < 3 ; j++){ 
           System.out.println(i + " " + j); 
         } 
       } 

       // Simulate the double for loop through recursion 
       System.out.println("Double for loop through recursion"); 
       iterate(0,0,3); 

     } 

} 

和輸出將是:

Double for loop 
0 0 
0 1 
0 2 
1 1 
1 2 
2 2 
Double for loop through recursion 
0 0 
0 1 
0 2 
1 1 
1 2 
2 2