递归有两个增量

时间:2014-10-31 18:43:40

标签: java arrays performance algorithm recursion

我正在尝试创建一个递归函数,允许我“模拟”一个双循环。类似于

的东西

迭代:

  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 个答案:

答案 0 :(得分: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相同。

答案 1 :(得分: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