【數論】C046_天機鎖(暴搜 / 枚舉)

一、Problem

在這裏插入圖片描述

19811435

二、Solution

方法一:暴搜

低級失誤:浪費了些許時間,一開始還看成了數字 2 只出現一次…

import java.util.*;
import java.math.*;
import java.io.*;
public class Main{
	static class Solution {
		int[] a;
		int N = 8;
		int res;
		boolean check() {
			int x4 = 0, x9 = 0, sum = 0;
			boolean x2 = false;
			for (int i = 0; i < a.length; i++) {
				if (a[i] == 4) x4++;
				if (a[i] == 9) x9++;
				if (a[i] == 2) x2 = true;
				sum += a[i];
			}
			return x4 == x9 && x2 && sum <= 52;
		}
		void dfs(int k) {
			if (k == N) {
				if (check())
					res++;
				return;
			}
			for (int i = 0; i <= 9; i++) {
				a[k] = i;
				dfs(k+1);
			}
		}
		void init() {
			Scanner sc = new Scanner(new BufferedInputStream(System.in));
			a = new int[N];
			dfs(0);
			System.out.println(res);
		}
	}
    public static void main(String[] args) throws IOException {  
        Solution s = new Solution();
		s.init();
    }
}

複雜度分析

  • 時間複雜度:O(...)O(...)
  • 空間複雜度:O(...)O(...)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章