java全排列算法實現 --- 小例子實現

Question:猜算式

看下面的算式:

□□ x □□ = □□ x □□□

它表示:兩個兩位數相乘等於一個兩位數乘以一個三位數。

如果沒有限定條件,這樣的例子很多。

但目前的限定是:這9個方塊,表示1~9的9個數字,不包含0。

該算式中1至9的每個數字出現且只出現一次!

比如:

46 x 79 = 23 x 158

54 x 69 = 27 x 138

54 x 93 = 27 x 186

.....

請編程,輸出所有可能的情況!

注意:

左邊的兩個乘數交換算同一方案,不要重複輸出!

不同方案的輸出順序不重要


思路:

        看到這道題的時候,立馬想到的是 使用暴力破解方法 進行解決,即:寫幾層for循環進行操作,但是,太繁瑣了,我就想,還有沒有其他思路,聯想到前段看過的全排列算法,然後,就使用這個思路進行編碼了,源碼如下:

/**
 * @ 郝志超
 *
 */
public class Question3 {
public static int total = 0; //記錄符合條件的算式個數

//交換兩個值
public static void swap(int[] intArrs, int i, int j) {
int temp;
temp = intArrs[i];
intArrs[i] = intArrs[j];
intArrs[j] = temp;
}

//全排列算法
public static void arrange(int[] intArrs, int st, int len) {
if (st == len - 1) {
if(intArrs[0] < intArrs[2]) {
if((intArrs[0] * 10 + intArrs[1]) * (intArrs[2] * 10 + intArrs[3]) == ((intArrs[4] * 10 + intArrs[5]) * (intArrs[6] * 100 + intArrs[7] * 10 + intArrs[8]))) {
System.out.println(intArrs[0] + "" + intArrs[1] + " * " + intArrs[2] + "" + intArrs[3] + " = " + intArrs[4] +""+ intArrs[5] + " * " + intArrs[6] + "" + intArrs[7] + "" + intArrs[8]);
total++;
}
}
// 打印所有全排列
/*for(int i = 0; i < len; i++) {
System.out.print(intArrs[i] + "  ");
}*/
} else {
for (int i = st; i < len; i++) {
swap(intArrs, st, i);
arrange(intArrs, st + 1, len);
swap(intArrs, st, i);
}
}
}
public static void main(String[] args) {
int intArrs[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
arrange(intArrs, 0, intArrs.length);
System.out.println(total);
}
}

打印結果:

46 * 79 = 23 * 158
54 * 69 = 27 * 138
54 * 93 = 27 * 186
58 * 67 = 29 * 134
58 * 69 = 23 * 174
58 * 73 = 29 * 146
58 * 96 = 32 * 174
63 * 74 = 18 * 259
64 * 79 = 32 * 158
73 * 96 = 12 * 584
76 * 98 = 14 * 532
11


 

發佈了28 篇原創文章 · 獲贊 21 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章