题目简介
解题思路
用dfs求1-9这9个数字全排列可以组成的数字 将数字分隔成两部分,分别为num1和num2 将num1和num2代入检验函数,如果符合题目要求则总方案数加一 注意乘数和被除数相同的情况,因此最后的方案数要除以2
java源码
public class Main {
public static boolean [ ] visited = new boolean [ 9 ] ;
public static char [ ] num = new char [ ] { '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' } ;
public static int cnt = 0 ;
public static String str = "" ;
public static void main ( String[ ] args) {
dfs ( 0 , str) ;
System. out. println ( cnt / 2 ) ;
}
private static void dfs ( int i, String str) {
if ( i == 9 ) {
split ( str) ;
} else {
for ( int j = 0 ; j < 9 ; j++ ) {
if ( ! visited[ j] ) {
visited[ j] = true ;
dfs ( i + 1 , str + num[ j] ) ;
visited[ j] = false ;
}
}
}
}
private static void split ( String str) {
int i;
for ( i = 0 ; i < 8 ; i++ ) {
String str1 = str. substring ( 0 , i + 1 ) ;
String str2 = str. substring ( i + 1 , 9 ) ;
int num1 = Integer. parseInt ( str1) ;
int num2 = Integer. parseInt ( str2) ;
check ( num1, num2) ;
}
}
private static void check ( int num1, int num2) {
int ans = num1 * num2;
String num = String. valueOf ( ans) ;
if ( num. length ( ) != 9 ) return ;
boolean [ ] checknum = new boolean [ 10 ] ;
while ( ans >= 10 ) {
int serial = ans % 10 ;
checknum[ serial] = true ;
ans /= 10 ;
}
checknum[ ans] = true ;
if ( checknum[ 0 ] ) return ;
else checknum[ 0 ] = true ;
for ( boolean flag : checknum) {
if ( ! flag) {
return ;
}
}
cnt++ ;
}
}