20天 hot 100 速通计划-day12

发布时间 2023-08-18 20:57:33作者: Ba11ooner

回溯

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 中的所有元素 互不相同

常规回溯,子集类型不带放回,需要引入 startIndex

class Solution {
public:
    vector<vector<int>> res; // 定义一个二维数组用于存放结果集
    vector<int> path; // 定义一个一维数组用于存放每个子集
    void backtrack(vector<int>& nums, int startIndex) { // 回溯函数
        res.push_back(path); // 将当前子集添加到结果集中
        if (startIndex > nums.size()) { // 如果startIndex超过数组长度,直接返回
            return;
        }
        for (int i = startIndex; i < nums.size(); i++) { // 遍历nums数组
            path.push_back(nums[i]); // 将当前元素添加到子集中
            backtrack(nums, i + 1); // 递归调用回溯函数,startIndex为i+1,用于获取当前元素之后的所有组合
            path.pop_back(); // 撤销选择,将当前元素从子集中移除
        }
    }
    vector<vector<int>> subsets(vector<int>& nums) { // 主函数
        res.clear(); // 清空结果集
        path.clear(); // 清空子集
        backtrack(nums, 0); // 调用回溯函数
        return res; // 返回结果集
    }
};

17. 电话号码的字母组合

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

img

示例 1:

输入:digits = "23"
输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]

示例 2:

输入:digits = ""
输出:[]

示例 3:

输入:digits = "2"
输出:["a","b","c"]

提示:

  • 0 <= digits.length <= 4
  • digits[i] 是范围 ['2', '9'] 的一个数字。
class Solution {
private:
    // 定义数字到字母的映射关系
    string letterMap[10] = {
        "",
        "",
        "abc",
        "def",
        "ghi",
        "jkl",
        "mno",
        "pqrs",
        "tuv",
        "wxyz"
    };
    string digits = "";  // 输入的数字串
    string path;         // 当前生成的字母组合
    vector<string> res;  // 存储所有字母组合的结果

    // 回溯函数
    void backtrack(int index) {
        // 如果已经遍历完所有数字,将当前的字母组合加入结果中
        if (index == digits.size()) {
            if (path != "")  // 需要判断当前字母组合非空,因为""没有对应的字母
                res.push_back(path);
            return;
        }

        // 获取当前数字对应的字母集合
        int digit = digits[index] - '0';
        string letters = letterMap[digit];

        // 遍历当前数字对应的字母集合,依次加入字母组合中
        for (int i = 0; i < letters.size(); i++) {
            // 将当前字母添加到字母组合中
            path.push_back(letters[i]);
            index++;
            // 继续回溯下一个数字
            backtrack(index);
            index--;
            // 撤销选择,去掉最后添加的字母,回溯到上一层
            path.pop_back();
        }
    }

public:
    vector<string> letterCombinations(string digits) {
        this->digits = digits;
        res.clear();  // 清空结果容器
        backtrack(0);  // 从第一个数字开始回溯
        return res;
    }
};

39. 组合总和

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。

candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。

对于给定的输入,保证和为 target 的不同组合数少于 150 个。

示例 1:

输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释:
2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。
仅有这两种组合。

示例 2:

输入: candidates = [2,3,5], target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]

示例 3:

输入: candidates = [2], target = 1
输出: []

提示:

  • 1 <= candidates.length <= 30
  • 2 <= candidates[i] <= 40
  • candidates 的所有元素 互不相同
  • 1 <= target <= 40
class Solution {
private:
    vector<int> path; // 用于存储当前的路径
    vector<vector<int>> res; // 用于存储所有结果
    int sum = 0; // 当前路径的总和
    void backtrack(vector<int>& candidates, int startIndex){
        if(sum < 0){ // 当路径和小于0时,说明这条路径已经不符合要求,直接返回
            return;
        }
        if(sum == 0){ // 当路径和等于0时,说明这是一条符合要求的路径,将其加入结果集中
            if(path.size() > 0) // 为了避免空解,只有当路径长度大于0时才加入结果集
                res.push_back(path);
            return;
        }
        for(int i = startIndex; i < candidates.size(); i++){ // 从startIndex开始遍历候选数组
            path.push_back(candidates[i]); // 将当前候选数加入路径
            sum -= candidates[i]; // 更新路径和
            backtrack(candidates, i); // 递归调用,startIndex为i,表示可以重复使用当前候选数
            sum += candidates[i]; // 恢复路径和
            path.pop_back(); // 回溯,将当前候选数从路径中移除
        }
    }
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        sum = target; // 初始化路径和
        path.clear(); // 清空路径
        res.clear(); // 清空结果
        backtrack(candidates, 0); // 回溯算法求解组合数之和
        return res; // 返回结果集
    }
};

22. 括号生成

数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。

示例 1:

输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]

示例 2:

输入:n = 1
输出:["()"]

提示:

  • 1 <= n <= 8
class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> res; // 存储结果的向量
        backtrack(res, "", 0, 0, n); // 回溯函数,初始传入空字符串和初始的括号数
        return res; // 返回结果
    }
    
    void backtrack(vector<string>& res, string curr, int open, int close, int max) {
        // 如果当前字符串长度等于2n,表示生成了一组有效的括号,将其加入结果向量中
        if (curr.length() == max * 2) {
            res.push_back(curr);
            return;
        }
        
        // 如果左括号数量小于n,可以继续添加左括号
        if (open < max) {
            backtrack(res, curr + "(", open + 1, close, max);
        }
        
        // 如果右括号数量小于左括号数量,可以继续添加右括号
        if (close < open) {
            backtrack(res, curr + ")", open, close + 1, max);
        }
    }
};

79. 单词搜索

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

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

示例 1:

img

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

示例 2:

img

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

示例 3:

img

输入: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
  • boardword 仅由大小写英文字母组成
class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {// 主函数,输入二维字符向量board和字符串word
        if (board.empty() || board[0].empty()) { // 如果board为空或者board的列数为空,直接返回false
            return false;
        }
        m = board.size(); // 获取board的行数
        n = board[0].size();// 获取board的列数
        visited.resize(m, vector<bool>(n, false)); // 初始化visited向量,标记每个元素是否被访问过,默认为false
        for (int i = 0; i < m; ++i) { // 遍历board的行
            for (int j = 0; j < n; ++j) { // 遍历board的列
                if (dfs(board, word, 0, i, j)) { // 调用dfs函数进行深度优先搜索
                    return true;
                }
            }
        }
        return false;
    }

private:
    int m, n; // 行数和列数
    vector<vector<bool>> visited; // 记录元素是否被访问过的向量
    bool dfs(vector<vector<char>>& board, const string& word, int index, int row, int col) { // dfs函数,用于判断board上的字符是否与word匹配
        if (index == word.size()) { // 如果index等于word的长度,说明已经找到匹配的路径
            return true;
        }
        if (row < 0 || row >= m || col < 0 || col >= n) { // 如果row和col超出board的范围,返回false
            return false;
        }
        if (visited[row][col] || board[row][col] != word[index]) { // 如果元素已经被访问过或者元素与当前匹配的字符不相等,返回false
            return false;
        }
        visited[row][col] = true; // 标记当前元素为已访问
        bool res = dfs(board, word, index + 1, row - 1, col) // 向上搜索
                || dfs(board, word, index + 1, row + 1, col) // 向下搜索
                || dfs(board, word, index + 1, row, col - 1) // 向左搜索
                || dfs(board, word, index + 1, row, col + 1); // 向右搜索
        visited[row][col] = false; // 恢复为未访问状态
        return res;
    }
};