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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章