🔥 LeetCode 热题 HOT 100: 78 && 79

80 阅读1分钟

“Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情。”

78. 子集

一、题目描述:

给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。

解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。

示例 1:

输入: nums = [1,2,3]
输出: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

示例 2:

输入: nums = [0]
输出: [[],[0]]

提示:

  • 1 <= nums.length <= 10
  • -10 <= nums[i] <= 10
  • nums 中的所有元素 互不相同

二、思路分析:

  • 回溯
  1. 结束条件( index == nums.length)
  2. 当前可以做的选择( 从起始 index 向后选择)
  3. 已经做出的选择

impicture_20210815_135238.png

三、AC 代码:

class Solution {
    List<List<Integer>> ans;
    public List<List<Integer>> subsets(int[] nums) {
        this.ans = new ArrayList<>();
        dfs(nums, 0, new ArrayList<>());
        return ans;
    }

    void dfs(int[] nums, int index, List<Integer> path){
        ans.add(new ArrayList<>(path));
        if(index == nums.length) return;

        for(int i = index; i<nums.length;i++){
            path.add(nums[i]);
            dfs(nums, i + 1, path);
            path.remove(path.size() - 1);
        }
    }
}

79. 单词搜索

一、题目描述:

给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。

单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。

 

示例 1:

输入: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
输出: true

示例 2:

输入: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
输出: true

示例 3:

输入: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
输出: false

 

提示:

  • m == board.length
  • n = board[i].length
  • 1 <= m, n <= 6
  • 1 <= word.length <= 15
  • board 和 word 仅由大小写英文字母组成

二、思路分析:

  • 回溯 尝试从网格的每一个位置出发搜索是否存在 单词 word

终止条件 : 当前字符不匹配 || 当前字符匹配并且到达字符末尾

可以做出的选择 : 当前位置的上下左右网格

三、AC 代码:

public boolean exist(char[][] board, String word) {
    int m = board.length;
    int n = board[0].length;

    boolean[][] visited = new boolean[m][n];
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            boolean ans = dfs(board, i, j, word, 0, visited);
            if (ans) return true;
        }
    }
    return false;
}

boolean dfs(char[][] board, int i, int j, String word, int index, boolean[][] visited) {
    if (board[i][j] != word.charAt(index)) {
        return false;
    } else if (index == word.length() - 1) {
        return true;
    }

    visited[i][j] = true;
    int[][] dir = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};


    for (int[] arr : dir) {
        int ni = arr[0] + i;
        int nj = arr[1] + j;
        if (ni < 0 || ni >= board.length || nj < 0 || nj >= board[0].length
                || visited[ni][nj]) continue;
        boolean ans = dfs(board, ni, nj, word, index + 1, visited);
        if (ans) return true;
    }

    visited[i][j] = false;
    return false;
}