【代码随想录二刷】Day25-回溯-C++

代码随想录二刷Day25

今日任务

216.组合总和III
17.电话号码的字母组合
语言:C++

216. 组合总和III

链接:https://leetcode.cn/problems/combination-sum-iii/

class Solution {
public:
    vector<vector<int>> res;
    vector<int> path;
    int curSum = 0;
    void backtracking(int k, int n, int cur){
        if(path.size() == k && curSum == n){
            res.push_back(path);
            return;
        }
        else if(path.size() < k && curSum >= n) return;
        else if(path.size() == k && curSum < n) return;

        for(int i = cur; i <= n && i <= 9; i++){
            curSum += i;
            path.push_back(i);
            backtracking(k, n, i + 1);
            curSum -= i;
            path.pop_back();
        }
    }
    vector<vector<int>> combinationSum3(int k, int n) {
        backtracking(k, n, 1);
        return res;
    }
};

17. 电话号码的字母组合

链接:https://leetcode.cn/problems/letter-combinations-of-a-phone-number/

class Solution {
public:
    vector<string> res;
    string path = "";
    const string map[10] = {
        "", //0
        "", //1
        "abc", //2
        "def", //3
        "ghi", //4
        "jkl", //5
        "mno", //6
        "pqrs", //7
        "tuv", //8
        "wxyz", //9
    };
    void backtracking(string digits, int index){
        if(index == digits.length()){
            res.push_back(path);
            return;
        }
        int tmp = digits[index] - '0';
        for(int i = 0; i < map[tmp].length(); i++){
            path += map[tmp][i];
            backtracking(digits, index + 1);
            path.pop_back();
        }
    }
    vector<string> letterCombinations(string digits) {
        if(digits.length() == 0) return res;
        backtracking(digits, 0);
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值