LeetCode_单周赛_337

6319. 奇偶位数

位运算模拟

class Solution {
    public int[] evenOddBit(int n) {
        int i = 0;
        int[] ans = new int[2];
        while (n > 0) {
            ans[i] += n & 1;
            n >>= 1;
            i ^= 1; // 0 变 1,1 变 0
        }

        return ans;
    }
}

6322. 检查骑士巡视方案

bfs

骑士的行动是从下标 0 开始的。
注意特判一下,只能从左上角出发,左上角不一定是 0,如果不是,直接返回 false

class Solution {
    private static int[] dx = {-2, -1, 1, 2, 2, 1, -1, -2}, dy = {1, 2, 2, 1, -1, -2, -2, -1};

    public boolean checkValidGrid(int[][] g) {
        if (g[0][0] != 0) return false; // 必须从左上角出发,左上角可能不是 0,就不满足条件
        int x = 0, y = 0;
        int cnt = 0, n = g.length;

        for (int i = 0; i < (n * n); i++) {
            for (int j = 0; j < 8; j++) {
                int nx = x + dx[j];
                int ny = y + dy[j];

                if (nx >= 0 && nx < n && ny >= 0 && ny < n && g[nx][ny] == cnt + 1) {
                    cnt++;
                    x = nx;
                    y = ny;
                    break;
                }
            }
        }

        return cnt == n * n - 1;
    }
}

6352. 美丽子集的数目

回溯+剪枝

回溯求子序列

class Solution {
    private static int ans, k, n;
    private static boolean[] vis = new boolean[3000];
    private static int[] nums;

    public int beautifulSubsets(int[] nums, int k) {
        ans = 0;
        this.nums = nums;
        n = nums.length;
        this.k = k;

        for (int i = 1; i <= n; i++) dfs(0, 0, i);

        return ans;
    }

    private static void dfs(int u, int m, int len) {
        if (m == len) {
            ans++;
            return;
        }

        for (int i = u; i < n; i++) {
            int x = nums[i];
            if (vis[x + k] || (x - k > 0 && vis[x - k])) continue;
            
            vis[x] = true;
            dfs(i + 1, m + 1, len);
            vis[x] = false;
        }
    }
}

6321. 执行操作后的最大 MEX

贪心,不会写,补题

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值