Letter Combinations of a Phone Number

来源:互联网 发布:淘宝好评能改差评吗 编辑:程序博客网 时间:2024/05/18 02:32

1、一个简单的动态规划;

lettercombination(string digits){    help(digits,i,len);}void help(string digits,int i,int len){    if(i==len)    {        str[len]='\0';        string temp=str;        res.push_back(temp);        return;    }    int j=digits[i]-'0';    for(int j=0;j<num[i].size();j++)    {        str[i]=num[i][j];        help(digits,i+1,len);    }}

题目:
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 {public:   vector<string> res;    string num[10];    char   str[1000];    vector<string> letterCombinations(string digits) {        int len=digits.length();        res.clear();        num[2]="abc";        num[3]="def";        num[4]="ghi";        num[5]="jkl";        num[6]="mno";        num[7]="pqrs";        num[8]="tuv";        num[9]="wxyz";        help(digits,0,len);        return res;    }    void help(string &digits,int i,int len)    {        if(i==len)        {            str[len]='\0';            string temp=str;            res.push_back(temp);            return;        }        int n=digits[i]-'0';        for(int j=0;j<num[i].size();j++)        {            str[i]=num[n][j];            help(digits,i+1,len);        }    }};
0 0
原创粉丝点击