枚举


枚举的效率在处理某些特定的问题还是比较高的

1.蓝桥杯

1.1 四平方和

解法一

2016年蓝桥杯javaB组省赛
题目来源:第8题

public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int flag = 1;
        for (int i = 0; i <= Math.sqrt(n); i++) {
            for (int j = 0; j <= Math.sqrt(n); j++) {
                for (int k = 0; k <= Math.sqrt(n); k++) {
                    for (int l = 0; l <= Math.sqrt(n); l++) {
                        if (i*i+j*j+k*k+l*l==n){
                            System.out.println(i+" "+j+" "+k+" "+l);
                            flag = 0;
                        }
                        if (flag==0) break;
                    }
                    if (flag==0) break;
                }
                if (flag==0) break;
            }
            if (flag==0) break;
        }
    }

总结:这道题也可以用递归来找到可能的结果

解法2

static int N;
	static Map<Integer, Integer> cache = new HashMap<Integer, Integer>();
 
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		N = sc.nextInt();
		for (int c = 0; c * c <= N / 2; ++c) { // 缓存
			for (int d = c; c * c + d * d <= N; ++d) {
				if (cache.get(c * c + d * d) == null) // 如果c^2 + d^2为空
					cache.put(c * c + d * d, c); // 存储c^2 + d^2
			}
		}
		for (int a = 0; a * a <= N / 4; ++a) {
			for (int b = a; a * a + b * b <= N / 2; ++b) {
				if (cache.get(N - a * a - b * b) != null) {
					int c = cache.get(N - a * a - b * b);
					int d = (int) sqrt(N - a * a - b * b - c * c);
					System.out.printf("%d %d %d %d\n", a, b, c, d);
					return;
				}
			}
		}
	}
posted @ 2021-04-07 17:07  木有呂朋友  阅读(12)  评论(0编辑  收藏  举报