对于1~9的九个数字,我们往中间插入乘号,它们的乘积也可能是1~9组成的一个排列,如:
132 * 965874 = 127495368
135627 * 948 = 128574396
612 * 954783 = 584327196
那么求它们的乘积最大是多少。
思路:直接对1~9执行全排列,每次拍好后尝试往中间插入乘号并计算它们的积,如果积只包含1~9且不存在重复数字,则与之前记录的最大值比较。
public class Main {
static boolean v[] = new boolean [10];
static int a[] = new int [9];
static int max = 0;
public static void main(String[] args) {
// TODO自动生成的方法存根
dfs(0);
System.out.println(max);
}
static void dfs (int i) {
if(i == 9) {//如果已经排好九个数字,则尝试往中间插入乘号,然后检查它们的积是否存在重复数字,并记录最大值
for(int j=0;j<8;j++) {
int t = getNum(j);
if(check(t) && t > max)
max = t;
}
return;
}
for (int j=1;j<10;j++)//尝试将没用过的数字放入当前位置
if (!v[j]) {
v[j] = true;
a[i] = j;
dfs(i+1);
v[j] = false;
}
}
static int getNum (int s) {//s表示乘号插入的位置,并返回两个数的积
int t1 = 0,t2 = 0;
for (int i=0;i<=s;i++)
t1 = t1 * 10 + a[i];
for (int i=s+1;i<9;i++)
t2 = t2 * 10 + a[i];
return t1 * t2;
}
static boolean check (int n) {//检查该数字是否只包含1~9且不存在重复数字
if(n < 100000000)
return false;
boolean v[] = new boolean[10];
while(n != 0) {
int t = n % 10;
if(t == 0)
return false;
if (v[t])
return false;
v[t] = true;
n /= 10;
}
return true;
}
}