蓝桥杯试题(一)----------凑算式
题目: 凑算式
A + B/C + DEF/GHI = 10
这个算式中A~I代表1~9的数字,不同的字母代表不同的数字。 比如:
6+8/3+952/714 就是一种解法,
5+3/1+972/486 是另一种解法。
这个算式一共有多少种解法?
一、直接暴力破解
/** * Created by Du on 2017/3/10. */ public class Main { public static void main(String args[]) { int ans = 0; double a,b,c,d,e,f,g,h,i; for(a=1.0;a<10.0;a++){ for (b=1.0;b<10.0;b++){ for (c=1.0;c<10.0;c++){ for (d=1.0;d<10.0;d++){ for (e=1.0;e<10.0;e++){ for (f=1.0;f<10.0;f++){ for (g=1.0;g<10.0;g++){ for (h=1.0;h<10.0;h++){ for (i=1.0;i<10.0;i++){ if ( a!=b&&a!=c&&a!=d&&a!=e&&a!=f&&a!=g&&a!=h&&a!=i &&b!=c&&b!=d&&b!=e&&b!=f&&b!=g&&b!=h&&b!=i &&c!=d&&c!=e&&c!=f&&c!=g&&c!=h&&c!=i &&d!=e&&d!=f&&d!=g&&d!=h&&d!=i &&e!=f&&e!=g&&e!=h&&e!=i &&f!=g&&f!=h&&f!=i &&g!=h&&g!=i &&h!=i){ if ((a+b/c+(d*100+e*10+f)/(g*100+h*10+i)==10.0)){ ans++; } } } } } } } } } } } System.out.print(ans); } }
算出来结果共有29种
二、DFS
/** * Created by Du on 2017/3/11. */ public class DFS { private static double[] a; private static boolean[] visit; private static int count = 0; public static void runDFS(int step){ a = new double[9]; visit = new boolean[9]; if (step == 9){ if (a[0]+a[1]/a[2]+(a[3]*100+a[4]*10+a[5])/(a[6]*100+a[7]*10+a[8])==10.0){ count++; } return; } for (int i=0;i<10;i++){ if (visit[i] == false){ a[step] = i+1.0; visit[i] = true; runDFS(step+1); visit[i] = false; } } return; } public static void main(String args[]){ runDFS(0); System.out.print(count); } }