2013-10-19 191 views
4

你好我想这个代码非递归我怎么能做到这一点?递归代码非循环递归

public class test { 

    public static void main(String[] args) { 
     int[] array = new int[]{0, 1, 2,3}; 
     int size = 2; 
     int[] tmp = new int[size]; 
     //Arrays.fill(tmp, -1); 
     generateCombinations(array, 0, 0, tmp); 
    } 

    private static void generateCombinations(int[] array, int start, int depth, int[] tmp) { 

     if (depth == tmp.length) { 
      for (int j = 0; j < depth; j++) { 
       System.out.print(array[tmp[j]]); 

      } System.out.println(); 
      return; 
     } 
     for (int i = start; i < array.length; i++) { 
      tmp[depth] = i; 
      generateCombinations(array, i + 1, depth + 1, tmp); 
     } 

    } 
} 

它从特定数字生成所有组合。

+1

到目前为止,您*尝试了什么?顺便说一句:我们在谈论什么编程语言?请将它添加到标签! –

+0

为什么你想要它是非递归的?递归是检查所有组合的一种通用方法。如果你的情况对于{0,1,2,3}非常具体,那么应该有一个三或四个循环的方法。 – nawfal

+0

因为是一个学校作业 – user2897452

回答

0

每个递归都可以重写为迭代,反之亦然。你只需要遵循共同的算法:

  1. 确定递归的基本情况。基本情况到达时,会导致递归结束。每个递归必须有一个定义的基地 的情况。另外,每次递归调用都必须朝向基本情况的 (否则递归调用将无限地执行 )。在我们的例子中,基本情况是n == 0.
  2. 实现一个循环,迭代直到达到基本情况。
  3. 在基本案例上取得进展。将新参数发送到循环的顶部,而不是递归方法。

这背后的是保持不变条件的概念。

0

试试这个:

public class Test { 
    private final int[] array; 
    private final int[] tmp; 

    private Test(int[] array, int size) { 
     tmp = new int[size]; 
     this.array = array; 
    } 

    public static void main(String[] args) { 
     Test t = new Test(new int[] {0, 1, 2, 3}, 2); 
     t.generateCombinations(); 
    } 

    /** 
    * Print the selection. 
    */ 
    private void print() { 
     for (int i : tmp) { 
      System.out.print(array[i]); 
     } 
     System.out.println(); 
    } 

    /** 
    * Set values in tmp for indices startIndex, ..., (tmp.length-1) 
    * to startValue, ..., (startValue-startIndex + tmp.length-1) 
    * @param startIndex 
    * @param startValue 
    */ 
    private void initMin(int startIndex, int startValue) { 
     final int offset = startValue - startIndex; 
     for (int i = startIndex; i < tmp.length; i++) { 
      tmp[i] = i+offset; 
     } 
    } 

    private void generateCombinations() { 
     if (tmp.length == 0) return; 
     initMin(0, 0); 
     print(); 

     final int maxIndex = tmp.length-1; 
     int index = maxIndex; 
     final int z = array.length-tmp.length; 

     while (index >= 0) { 
      if (tmp[index] == index+z) { 
       index--; 
      } else { 
       if (tmp[index]== index+z-1) { 
        // only value at index changes 
        tmp[index]++; 
        index--; 
       } else { 
        initMin(index, tmp[index]+1); 
        index = maxIndex; 
       } 

       print(); 
      } 
     } 
    } 
} 

该算法是基于以下观察: tmp[i]必须至多(i+array.length-tmp.length)

的算法总是总是在最后的位置,在此仍有可能加1并将以下位置的值设置为尽可能最小的值。