day 22| 77. 组合,216.组合总和III ,17.电话号码的字母组合

 77. 组合

77. 组合 - 力扣(LeetCode)

class Solution {
public:
    void combine(int begin, int n, int k, vector<vector<int>> &ans, vector<int> &path){
        if(path.size() == k){
            ans.push_back(path);  // 符合要求的path
        }
        for(int i = begin; i <= n; i++){
            path.push_back(i);
            combine(i + 1, n, k, ans, path);
            path.pop_back();
        }
    }
    vector<vector<int>> combine(int n, int k) {
        vector<vector<int>> ans;
        vector<int> path;
        int begin = 1;
        combine(begin, n, k, ans, path);
        return ans;
    }
};

216.组合总和III

216. 组合总和 III - 力扣(LeetCode)

class Solution {
public:
    void combinationSum3(int k, int n, int begin, int &sum, vector<int>& path, vector<vector<int>>& ans){
        if(sum == n && path.size() == k){
            ans.push_back(path);
        }
        for(int i = begin; i <= 9; i++){
            sum += i;
            path.push_back(i);
            combinationSum3(k, n, i + 1, sum, path, ans);
            path.pop_back();
            sum -= i;
        }
    }
    vector<vector<int>> combinationSum3(int k, int n) {
        vector<vector<int>> ans;
        vector<int> path;
        int sum = 0;
        combinationSum3(k, n, 1, sum, path, ans);  // 回溯
        return ans; 
    }
};

17.电话号码的字母组合

17. 电话号码的字母组合 - 力扣(LeetCode)

class Solution {
public:
    unordered_map<char, string> mp{{'2', "abc"}, {'3', "def"}, {'4', "ghi"}, {'5', "jkl"}, {'6', "mno"}, 
    {'7', "pqrs"}, {'8', "tuv"}, {'9', "wxyz"}};
    void letterCombinations(vector<string> words, int i, int n, vector<string>& ans, string& path){
        if(i >= n){
            return ;
        }
        for(char word : words[i]){  // 遍历这一层的字符串
            path.push_back(word);
            if(i < n - 1){
                letterCombinations(words, i + 1, n, ans, path);
            }else{
                ans.push_back(path); // 最后一层
            }
            path.pop_back();
        }
    } 
    vector<string> letterCombinations(string digits) {
        vector<string> words, ans;
        for(char ca : digits){
            words.push_back(mp[ca]);
        }
        string path;
        int n = words.size();
        letterCombinations(words, 0, n, ans, path);
        return ans;
    }
};

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值