搜索题也可以不搜索(洛谷P1149题题解,Java语言描述)

题目要求

P1149题目链接

在这里插入图片描述
在这里插入图片描述

分析

看起来要搜索,但何必呢?不搜也行啊~

其实我们预先把每一位的数值(0~9)算出来就好,分别是这样的:

  • key = 0, value = 6
  • key = 1, value = 2
  • key = 2, value = 5
  • key = 3, value = 5
  • key = 4, value = 4
  • key = 5, value = 5
  • key = 6, value = 6
  • key = 7, value = 3
  • key = 8, value = 7
  • key = 9, value = 6

当然,用数组就可以啦~~

接下来根据这个每一个数值的火柴棒数就可以根据每一位的累加出来啦,开一个循环即可。

最后我们可以根据输入的num,开双层循环进行遍历,暴力枚举所有可能,找到合适的答案,计数器数值+1。

不要忘记加号有两根火柴,等号也有两根火柴就好啦!!

我们保证24根火柴的情况能包含起来就行了。

AC代码(Java语言描述)

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int[] num_array = new int[2001], basic_array = {6, 2, 5, 5, 4, 5, 6, 3, 7, 6};
        num_array[0] = 6;
        Scanner scanner = new Scanner(System.in);
        int num = scanner.nextInt();
        scanner.close();
        //求每个数需要的火柴棒数量
        for(int i = 1; i <= 2000; i++) {
            int temp = i;
            while(temp >= 1) {
                num_array[i] += basic_array[temp%10];
                temp = temp/10;
            }
        }
        int counter = 0;
        //暴力枚举判断等式是否符合要求
        for(int i = 0; i <= 1000; i++) {
            for(int j = 0; j <= 1000; j++) {
                //加号算2个等号算2个
                if(num_array[i] + num_array[j] + num_array[i+j] + 4 == num) {
                    counter++;
                }
            }
        }
        System.out.println(counter);
    }
}
发布了369 篇原创文章 · 获赞 626 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/weixin_43896318/article/details/104085302