【无标题】

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

216. 组合总和III

题目链接

提交代码

class Solution {
public:
    vector<int> path;
    vector<vector<int>> result;
    void backtracking(int target, int sum, int index, int k)
    {
        if(k == path.size())
        {
            if(target == sum)
                result.push_back(path);
            return;
        }
        if(target < sum) return;
        for(int i = index; i <= 9 - (k - path.size()) + 1; i++)
        {
            sum += i;
            path.push_back(i);
            backtracking(target, sum, i + 1, k);
            sum -= i;
            path.pop_back();
        }
    }
    vector<vector<int>> combinationSum3(int k, int n) {
        if(n < k || n > 9 * k) return result;
        backtracking(n, 0, 1, k);
        return result;
    }
};

17.电话号码的字母组合

题目链接

提交代码

class Solution {
public:
    string dist[10] = {"", "", "abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
    vector<string> result;
    string path = "";
    void backtracking(string digits, int index){
        if(index == digits.size())
        {
            result.push_back(path);
            return;
        }
        int cur = digits[index] - '0';
        string letters = dist[cur];
        for(int i = 0; i < letters.size(); i++)
        {
            path += letters[i];
            backtracking(digits, index + 1);
            path.pop_back();
        }
    }
    vector<string> letterCombinations(string digits) {
        backtracking(digits, 0);
        return result;
    }
};

总结

                     日期: 2023 年 4 月 8 日
              学习时长: 0 h 30 m
                     难度: ★ \bigstar
累计完成题目数量: 66
距离目标还有数量: 234
                      小结:

  1. 第一题sum和target的判断条件写反了,搞得我找了半天错误

你可能感兴趣的:(算法)