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;
}
}
}