2016-03-04 51 views
0

我想寫一個打印這些 號碼的所有可能安排一個遞歸方法,整數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); 
} 
+0

[算法找到下一個給定的字符串的更大排列]可能的重複(http://stackoverflow.com/questions/1622532/algorithm-to-find-next-greater-permutation-of-a-given-string ) – Prune

+0

如果您搜索「Java陣列排列」,您會發現許多針對此問題的通用解決方案。 – Prune

回答

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,否則你只會傳遞相同的數組,並覆蓋以前的排列。

0

將值傳遞給數組,隨機化並創建一個循環來生成矩陣。 循環:做一個通用的循環開始產生與I0矩陣,J0喜歡的位置I1,第j1 matrixand添加陣列

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