代码随想录算法训练营第二十五天 | 216.组合总和III,17.电话号码的字母组合

代码随想录算法训练营第二十五天 | 216.组合总和III,17.电话号码的字母组合

1.1 216.组合总和III

思路:

  1. 添加一个返回的限制
class Solution {
private:
    vector<vector<int>> res;
    vector<int> path;

    void backtracking(int target, int k, int startIndex){
        if(path.size() == k){
            if(target == 0) res.push_back(path);
            return;
        }
        for(int i = startIndex; i <= 9; ++i){
            path.push_back(i);
            backtracking(target - i, k, i+1);
            path.pop_back();
        }
    }
public:
    vector<vector<int>> combinationSum3(int k, int n) {
        backtracking(n, k, 1);
        return res;
    }
};

思路:

  1. 优化一:已经超出目标值
  2. 优化二:剩下的值的个数不满足要求
class Solution {
private:
    vector<vector<int>> res;
    vector<int> path;

    void backtracking(int target, int k, int startIndex){
        if(target < 0) return;
        if(path.size() == k){
            if(target == 0) res.push_back(path);
            return;
        }
        for(int i = startIndex; i <= 9 - (k - path.size()) + 1; i++){
            path.push_back(i);
            backtracking(target - i, k, i+1);
            path.pop_back();
        }
    }
public:
    vector<vector<int>> combinationSum3(int k, int n) {
        backtracking(n, k, 1);
        return res;
    }
};

1.2 17.电话号码的字母组合

思路:

  1. 本题每一个数字代表的是不同集合,也就是求不同集合之间的组合
class Solution {
private:
    vector<string> board = {"", "", "abc", "def", "ghi","jkl","mno","pqrs","tuv","wxyz"};
    vector<string> res;
    string s;
    void backtracking(int pos, string digits){
        if(pos == digits.size()){
            res.push_back(s);
            return;
        }
        int num = digits[pos] - '0';
        for(int i=0; i < board[num].size(); ++i){
            s.push_back(board[num][i]);
            backtracking(pos+1, digits);
            s.pop_back();
        }
    }
public:
    vector<string> letterCombinations(string digits) {
        if(digits.size() == 0) return {};
        backtracking(0, digits);
        return res;
    }
};
  • 时间复杂度: O(3^m * 4^n),其中 m 是对应四个字母的数字个数,n 是对应三个字母的数字个数
  • 空间复杂度: O(3^m * 4^n)

你可能感兴趣的:(刷题打卡,算法)