[LeetCode.17]电话号码的字母组合

思路:使用回溯+递归

code:

class Solution 
{
public:
    /*
     * @param digits: A digital string
     * @return: all posible letter combinations
     */
    vector<string> letterCombinations(string digits) 
    {
        // write your code here
        if (digits.size() <= 0) 
        {
            return vector<string>();
        }
        vector<string> result;
        string str;
        letterCombinations(digits, str, 0, result);
        return result;
    }


    void letterCombinations(string &digits, string &str, int index, vector<string> &result) 
    {
        if (index == digits.size()) 
        {
            result.push_back(str);
//            str.clear();
            return;
        }
        string base[] = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
        for (int i = 0; i < base[digits[index] - '0'].size(); i++) 
        {
            str += base[digits[index] - '0'][i];
            letterCombinations(digits, str, index + 1, result);
            str.pop_back();            //使用回溯
        }
    }
};

转自:https://www.cnblogs.com/libaoquan/p/7381348.html

如有不当之处,请联系我:[email protected]

猜你喜欢

转载自blog.csdn.net/weixin_39460182/article/details/80277935