zoukankan      html  css  js  c++  java
  • Letter Combinations of a Phone Number——简单的回溯算法

     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.

    Input:Digit string "23"
    Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
    

    Note:
    Although the above answer is in lexicographical order, your answer could be in any order you want.

    class Solution {
    private:
        vector<string> res;
        string temp;
    public:
        void getRes(string digits,int len,map<char,string> num_map,int index)
        {
            if(index>=len)
            {
                res.push_back(temp);
                return; 
            }
            char   strNum=digits[index];
            string strLetter=num_map[strNum];
            for(int j=0;j<strLetter.size();j++)
            {
                temp.push_back(strLetter[j]);
                getRes(digits,len,num_map,index+1);
                temp.pop_back();
            }
            
        }
        vector<string> letterCombinations(string digits) {
            map<char,string> num_map;
            num_map['0']="";
            num_map['1']="";
            num_map['2']="abc";
            num_map['3']="def";
            num_map['4']="ghi";
            num_map['5']="jkl";
            num_map['6']="mno";
            num_map['7']="pqrs";
            num_map['8']="tuv";
            num_map['9']="wxyz";
            int len=digits.size();
            if(len==0)
                return res;
            getRes(digits,len,num_map,0);
            return res;
        }
    };
  • 相关阅读:
    c++STL容器之deque容器
    c++STL容器之vector容器
    c++STL容器之string容器
    c++之STL基本认识
    c++之类模板案例
    c++之类模板和友元
    c++之类模板分文件编写
    c++之类模板成员函数的类外实现
    c++类模板与继承
    c++之类模板对象作函数参数
  • 原文地址:https://www.cnblogs.com/qiaozhoulin/p/4547456.html
Copyright © 2011-2022 走看看