题目地址
思路:
先枚举数字1~9可能出现的组合形式,再双重循环分离出a,b,c,满足题目要求a + b /c == n.
慎用java的String 转 Integer函数,易超时.
因为是9个数字,复杂度为O(9!)
// package ch01;
import java.util.Scanner;
public class Main {
public static long gcd(long fm, long fm2)
{return fm2 == 0 ? fm : gcd (fm2, fm % fm2);}
public static int n, cnt;
public static int vis[] = new int[10 + 5];
public static int a[] = new int[10 + 5];
public static int trans(int l , int r) {
int ans = 0;
for(int i = l;i <= r;i++)
ans = ans * 10 + a[i];
return ans;
}
public static void dfs(int k) {
if(k == 9) {
// for(int i = 1;i <= 9;i++) {
// System.out.print(a[i] + " ");
// }
// System.out.println();
//
for(int i = 1;i <= k - 2;i++)
for(int j = i + 1;j <= k - 1;j++)
{
int a = trans(1, i);
int b = trans(i + 1, j);
int c = trans(j + 1, k);
if(b % c == 0 && a + b /c == n)cnt++;
}
} else {
for(int i = 1;i <= 9;i++) {
if(vis[i] == 0)
{
a[k + 1] = i;
vis[i] = 1;
dfs(k + 1);
vis[i] = 0;
}
}
}
}
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
n = cin.nextInt();
dfs(0);
System.out.println(cnt);
}
}