2021.1.11每日复习 78.子集(DFS+二进制位)+ 79.单词搜索(DFS)

78.子集(DFS+二进制位)

在这里插入图片描述

class Solution {

	//DFS
    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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值