leetcode17---Letter Combinations of a Phone Number

来源:互联网 发布:淘宝蓝字海外直供 编辑:程序博客网 时间:2024/05/16 08:21

问题描述:
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"].

代码:

#include <iostream>#include<vector>using namespace std;class Solution {public:    vector<string> letterCombinations(string digits){        if(digits.size()==0) return {};        vector<string> ret;        string partRet;        dfs(digits, 0, partRet, ret);        return ret;    }    //深度优先搜索!!!    void dfs(string &digits, int curDeep, string &partRet, vector<string> &ret)    {//0=<curDeep<digits.size(),curDeep遍历字符串数组str[](第一层遍历)        const string str[]={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};        if(curDeep == digits.size())        {            ret.push_back(partRet);            return;        }//如digits[curDeep]='2',则str[2]="abc",str[2].size()=3        for(int i=0;i<str[digits[curDeep]-'0'].size();i++)        {//str[digits[curDeep]-'0']遍历字符串数组str[]中的每个字符串            partRet += str[digits[curDeep]-'0'][i];            dfs(digits, curDeep+1, partRet, ret);            //partRet.pop_back();基本c++不支持pop_back()            //所以,删掉字符串最后一个元素可以采用以下方法            partRet=partRet.substr(0,partRet.size()-1);        }    }};int main(){    Solution s;    string digits="23";    vector<string> ret;    ret = s.letterCombinations(digits);    for(int i=0;i<ret.size();i++)    {        cout<<ret[i]<<endl;    }    return 0;}
0 0
原创粉丝点击