Leetcode 17. Letter Combinations of a Phone Number
- 题目
- 解析
题目
解析
这题实际上是一个无重复combination的模板题,只需要对1做一下特殊处理即可
关于combination和permutation的总结,看这里:
代码:
class Solution:def letterCombinations(self, digits: str) -> List[str]:def backtracking(comb,level):if level==len(digits):ans.append(comb[:])returnfor c in d[digits[level]]:#comb.appned(c)backtracking(comb+c,level+1)#comb.pop()d = {
'2':['a','b','c'],'3':['d','e','f'],'4':['g','h','i'],'5':['j','k','l'],'6':['m','n','o'],'7':['p','q','r','s'],'8':['t','u','v'],'9':['w','x','y','z']}if not digits:return []ans = []backtracking('',0)return ans
C++版本:
注意一下unordered_map的直接初始化
class Solution {
public:vector<string> letterCombinations(string digits) {
if(digits.size() < 1) return {
};unordered_map<char,string> mapping{
{
'2',"abc"},{
'3',"def"},{
'4',"ghi"},{
'5',"jkl"},{
'6',"mno"},{
'7',"pqrs"},{
'8',"tuv"},{
'9',"wxyz"}};vector<string> ans;backtracking(mapping,ans,digits,0,"");return ans;}void backtracking(unordered_map<char,string>& mapping, vector<string>& ans, string digits, int level, string curr){
if(level == digits.size()){
ans.push_back(curr);return;}// for(int i=level;i<digits.size();i++){
for(auto c : mapping[digits[level]]){
curr += c;backtracking(mapping,ans,digits,level+1,curr);curr.pop_back();}// }}
};