《Linux命令列大全》重點筆記——第三部分 常見任務和主要工具
阿新 • • 發佈:2021-01-31
題目描述
這個算式中A-I代表1~9的數字,不同的字母代表不同的數字。
比如:
6+8/3+952/714 就是一種解法,
5+3/1+972/486 是另一種解法。
這個算式一共有多少種解法?
解決方法
public class B_3 {
public static ArrayList<Integer> path = new ArrayList<>();
public static int num;
public static void backtracking(int[] arr,boolean[] used) {
if (path.size()==3) {
if(path.get(0)+(path.get(1)/path.get(2))>=10)
return;
}
if(path.size()==arr.length) {
test(path);
return;
}
for (int i = 0; i < arr.length; i++) {
if(used[i]) continue;
used[i] = true;
path.add(arr[i]);
backtracking(arr, used);
path.remove(Integer. valueOf(arr[i]));
used[i] = false;
}
}
private static void test(ArrayList<Integer> p) {
double t1 = p.get(0);
double t2 = p.get(1)/(double)p.get(2);
int a1 = 100*p.get(3)+10*p.get(4)+p.get(5);
int a2 = 100*p.get(6)+10*p.get(7)+p.get(8);
double t3 = a1/(double)a2;
if(t1+t2+t3==10) {
num++;
System.out.println(p);
}
}
public static void main(String[] args) {
int[] a = {1,2,3,4,5,6,7,8,9};
boolean[] used = {false,false,false,false,false,false,false,false,false};
backtracking(a, used);
System.out.println(num);
}
}