LeetCode 之 Letter Combinations of a Phone Number

来源:互联网 发布:淘宝卖家违规扣分 编辑:程序博客网 时间:2024/06/06 18:52

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.

这个题其实就是一个深度搜索,假如我输入345则有:


设一个深度值(其实就是按的电话号码的第i位),用一个nextResult代表下一层返回来的string的vector,对这个vector里的数据,用本层的字符串的每一个char都插在前面,然后假如result,返回。这里需要注意的是对下一层返回的字符串每一个都要使用多次,所以注意要用一个temp来每次都copy一次。

代码(12ms):

class Solution {public:    string  digitString [10]={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};        vector<string> letterCombinations(string digits) {        vector <string>result;        if(digits=="") result.push_back("");         else result = DFS(digits,0);        return result;    }        vector<string> DFS(string digits , int depth){        vector<string>result;        if(digits.size()==0) return result;        //当前处理的char转为int        int current = digits[depth]-'0';        if(depth == digits.size()-1){            for(int i =0 ;i<digitString[current].size();i++){                result.push_back(digitString[current].substr(i,1));            }            return result;        }        //获取下一层的数据        vector<string>nextResult=DFS(digits,depth+1);        for(int i=0 ;i < nextResult.size();i++){            for(int j =0 ;j < digitString[current].size();j++){                //对下一层的每一个string都加一个本层的char,放在vector里                string temp = nextResult[i];                temp.insert(0,digitString[current].substr(j,1));                result.push_back(temp);            }        }        return result;            }};


0 0