Problem Description
100 can be expressed as a fraction: 100 = 3 + 69258 / 714.
It can also be expressed as: 100 = 82 + 3546 / 197.
Note the feature: In the band score, the numbers 1 to 9 appear respectively and only once (excluding 0).
Like this with fractions, 100 has 11 representations.
input format
Read a positive integer N (N<1000*1000) from standard input in
output format
The program outputs the numbers 1 to 9 without repetition or omission to form all kinds of numbers represented by fractions.
Note: It is not required to output every representation, only count how many representations there are!
Sample Input 1
100
Sample Output 1
11
Sample Input 2
105
Sample Output 2
6
Solve:
import java.util.Scanner;
/**
* @author 作者 : Cactus
* @version 创建时间:2018-3-26 上午07:47:23
* 深搜+全排列
*/
public class Main {
private static int N,count = 0;
private static int[] arrFlag = new int[10];
private static int[] arrNum = new int[10];
static int q = 0;
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
sc.close();
dfs(1);
System.out.println(count);
}
private static void dfs(int deep){ //深搜
if(deep == 10){
check(); //完成一套排列组合则检查一下
}else{
for(int i = 1; i <= 9; i++){
if(arrFlag[i] == 0){
arrFlag[i] = 1;
arrNum[deep] = i;
dfs(deep+1);
arrFlag[i] = 0;
arrNum[deep] = 0;
}
}
}
}
/**
* 深搜过程如下:
* 1 2 3 4 5 6 7 8 9
* 检查,然后回退,再赋值
1 2 3 4 5 6 7 9 8
1 2 3 4 5 6 8 7 9
1 2 3 4 5 6 8 9 7
1 2 3 4 5 6 9 7 8
1 2 3 4 5 6 9 8 7
1 2 3 4 5 7 6 8 9
1 2 3 4 5 7 6 9 8
1 2 3 4 5 7 8 6 9
1 2 3 4 5 7 8 9 6
1 2 3 4 5 7 9 6 8
1 2 3 4 5 7 9 8 6
1 2 3 4 5 8 6 7 9
1 2 3 4 5 8 6 9 7
1 2 3 4 5 8 7 6 9
1 2 3 4 5 8 7 9 6
1 2 3 4 5 8 9 6 7
1 2 3 4 5 8 9 7 6
1 2 3 4 5 9 6 7 8
1 2 3 4 5 9 6 8 7
1 2 3 4 5 9 7 6 8
......
*/
private static void check(){
for(int i = 1; i <= 8; i++){
int a = sum(1,i); //得到第一个整数
if(a >= N){
return;
}
for(int j = i + 1; j < 9; j++){
int b = sum(i + 1, j); //得第二数的分子
int c = sum(j + 1, 9); //得第二数的分母
if(c == 0){
continue;
}
if(b > c && b % c == 0 && N == a + b / c){ //判断条件
count++;
}
}
}
}
private static int sum(int a, int b){// 根据arrNum中的部分数值,得到对应的整数
int sum = 0;
for(int i = a; i <= b; i++){
sum = sum * 10 + arrNum[i];
}
return sum;
}
}