DFS类题目汇总

Posted by 谢玄xx on March 30, 2022

问题一:电话号码的字母组合

解题思路

代码

class Solution {
    vector<string> ans;
    string strs[10] = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
public:
    vector<string> letterCombinations(string digits) {
        if(digits.length() == 0) return ans;
        dfs(digits,0,"");
        return ans;
    }
    void dfs(string digits, int index, string combine){
        if(index == digits.length())
        {
            ans.push_back(combine);
            return ;
        }
        string s = strs[digits[index] - '0'];
        for(int i = 0; i < s.length(); i++)
        {
            combine.push_back(s[i]);
            dfs(digits, index + 1, combine);
            combine.pop_back();
        }

    }

};