如何使用递归方法查找所有可能的数字

时间:2016-03-04 16:28:09

标签: java recursion methods

我想编写一个Recursion方法,打印所有可能的安排 数字,整数1到9

随机排列在三行三列的网格中。例如:

6   2   1

5   4   7

3   9   8
抱歉,我没有任何代码,因为这对我来说很难。

public class Test {

public static void main (String[] args){
     String x = "123456789";
    System.out.println(test(x,0));


}
public static String test(String x , int y){

    if(x.length()==1)return "";

    return x.charAt(y)+test(x.substring(y),y);
}   

2 个答案:

答案 0 :(得分:0)

将值传递给数组,随机化并创建循环以生成矩阵。 循环:使一个通用循环开始生成矩阵与i0,j0像位置i1,j1的矩阵并添加数组的值

int j = 0;
 for( int i = 0; i <= YOURARRAY.length(); i++)
   {
System.out.println(   i POSITIONOFARRAY   );
j+1
   }

答案 1 :(得分:0)

有很多方法可以实现这样的事情,这是一个例子。为方便起见,我将使用int[]代替String

public static void main(String[] args) {
    nextPermutation(new int[9], 0, new boolean[9]);
}

public static void nextPermutation(int[] perm, int index, boolean[] alreadyUsed) {
    if(index == perm.length) {
        //the permutation is complete
        //you can store it or print it
    } else {

        for(int i = 0 ; i < alreadyUsed.length ; i++) {
            if(alreadyUsed[i]) continue;

            perm[index] = i+1;

            boolean[] newAlreadyUsed = Arrays.copyOf(alreadyUsed, alreadyUsed.length);
            newAlreadyUsed[i] = true;
            nextPermutation(Arrays.copyOf(perm, perm.length), index+1, Arrays.copyOf(newAlreadyUsed, newAlreadyUsed.length));
        }
    }
}

这将生成1-9的所有可能组合。该算法的想法是,您可以跟踪已经使用的数字,运行循环并选择所有可用的数字。

请注意,传递permalreadyUsed副本非常重要,否则您只需传递相同的数组并覆盖之前的排列。