17. Letter Combinations of a Phone Number[M]电话号码的字母组合

题目

Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.

思路

思路一:递归法

首先建立电话按钮上数字与字母的对应关系,很容易就想到了利用C++里map

思路二:回溯法

Tips

递归法

回溯法

C++

  • 思路一
    map<int,string> table={{2,"abc"},{3,"def"},{4,"ghi"},{5,"jkl"},{6,"mno"},{7,"pqrs"},{8,"tuv"},{9,"wxyz"}};
    
    vector<string> letterCombinations(string digits) {
        
        vector<string> result;
        
        if(digits.length()==0)
            return result;
            
        
        combineNum(result,0,"",digits);
        
        return result;
    }
    
    void combineNum(vector<string>& r,int count,const string& a,const string& b){
    
        if (count == b.size()){
          r.push_back(a);
          return;
        }

        string curStr = table[b[count] - '0'];
	
        for (char s : curStr){ 
            combineNum(r, count + 1, a + s, b);
        }   
    }
  • 思路二

python

posted @ 2019-06-09 14:48  风雪初晴,宜下江南  阅读(193)  评论(0编辑  收藏  举报