2014-10-31 62 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