標籤:rgs tostring stringbu port 演算法 buffer 輸出 void step
目錄
1 問題描述
2 解決方案
1 問題描述
看下面的算式:
□□ 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
.....
請編程,輸出所有可能的情況!
注意:
左邊的兩個乘數交換算同一方案,不要重複輸出!
不同方案的輸出順序不重要
2 解決方案
1 import java.util.ArrayList; 2 3 public class Main { 4 public static ArrayList<String> list = new ArrayList<String>(); 5 6 public void swap(int[] A, int i, int j) { 7 int temp = A[i]; 8 A[i] = A[j]; 9 A[j] = temp;10 }11 12 public void check(int[] A) {13 int a = A[0] * 10 + A[1];14 int b = A[2] * 10 + A[3];15 int c = A[4] * 10 + A[5];16 int d = A[6] * 100 + A[7] * 10 + A[8];17 if(a > b) {18 int temp = a;19 a = b;20 b = temp;21 }22 if(a * b == c * d) {23 StringBuffer s = new StringBuffer("");24 s.append(a);25 s.append(" x ");26 s.append(b);27 s.append(" = ");28 s.append(c);29 s.append(" x ");30 s.append(d);31 if(!list.contains(s.toString()))32 list.add(s.toString());33 }34 }35 36 public void dfs(int[] A, int step) {37 if(step == A.length) {38 check(A);39 return;40 } else {41 for(int i = step;i < A.length;i++) {42 swap(A, i, step);43 dfs(A, step + 1);44 swap(A, i, step);45 }46 }47 }48 49 public static void main(String[] args) {50 Main test = new Main();51 int[] A = {1,2,3,4,5,6,7,8,9};52 test.dfs(A, 0);53 for(int i = 0;i < list.size();i++)54 System.out.println(list.get(i));55 }56 }
運行結果:
46 x 79 = 23 x 15854 x 69 = 27 x 13854 x 93 = 27 x 18658 x 67 = 29 x 13458 x 69 = 23 x 17458 x 73 = 29 x 14658 x 96 = 32 x 17463 x 74 = 18 x 25964 x 79 = 32 x 15873 x 96 = 12 x 58476 x 98 = 14 x 532
演算法筆記_220:猜算式(Java)