78.子集(DFS+二进制位)
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if(nums.length < 1) return res;
Deque<Integer> path = new ArrayDeque<>();
dfs(nums, 0, path, res);
return res;
}
public void dfs(int[] nums, int n, Deque<Integer> path, List<List<Integer>> res) {
res.add(new ArrayList<>(path));
for(int i = n; i < nums.length; i++) {
path.addLast(nums[i]);
dfs(nums, i + 1, path, res);
path.removeLast();
}
}
public static List<List<Integer>> binaryBit(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
for (int i = 0; i < (1 << nums.length); i++) {
List<Integer> sub = new ArrayList<Integer>();
for (int j = 0; j < nums.length; j++)
if (((i >> j) & 1) == 1) sub.add(nums[j]);
res.add(sub);
}
return res;
}
}
79.单词搜索(DFS)
class Solution {
int m;
int n;
int[][] position = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
boolean[][] marked;
public boolean exist(char[][] board, String word) {
m = board.length;
n= board[0].length;
marked = new boolean[m][n];
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(dfs(board, i, j, 0, word)) return true;
}
}
return false;
}
public boolean dfs(char[][] board, int row, int col, int start, String word) {
if(start == word.length() - 1) {
return board[row][col] == word.charAt(start);
}
if(board[row][col] == word.charAt(start)) {
marked[row][col] = true;
for(int i = 0; i < 4; i++) {
int newX = row + position[i][0];
int newY = col + position[i][1];
if(inArea(newX, newY) && !marked[newX][newY]) {
if(dfs(board, newX, newY, start + 1, word)) return true;
}
}
marked[row][col] = false;
}
return false;
}
public boolean inArea(int x, int y) {
return x >= 0 && x < m && y >= 0 && y < n;
}
}