LeetCode Letter Combinations of a Phone Number (DFS)

题意

Given a digit string, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. 给定数字,输出所有可能的字母组合

解法

可以先将数字对应的字母存好,然后遍历输出就可以。只不过不用递归来写好像比较麻烦,这里用了一个DFS。

class Solution
{
public:
    vector<string> letterCombinations(string digits)
    {
	    static vector<vector<char>>	table = {
		    					{},{},
							{'a','b','c'},
							{'d','e','f'},
							{'g','h','i'},
							{'j','k','l'},
							{'m','n','o'},
							{'p','q','r','s'},
							{'t','u','v'},
							{'w','x','y','z'}
	    					};
	    vector<string>	rt;
	    string	temp;
	    dfs(digits,table,rt,0,digits.size(),temp);
	    return	rt;
    }

    void	dfs(string digits,vector<vector<char>> table,vector<string> & ans,int k,int length,string temp)
    {
	    if(k >= length && temp.size())
	    {
		    ans.push_back(temp);
		    return;
	    }

	    for(int i = 0;i < table[digits[k] - '0'].size();i ++)
	    {
		    temp += table[digits[k] - '0'][i];
		    dfs(digits,table,ans,k + 1,length,temp);
		    temp.pop_back();
	    }
    }
};
原文地址:https://www.cnblogs.com/xz816111/p/5857220.html