您的位置:首页 > 编程语言 > C语言/C++

Letter Combinations of a Phone Number

2017-04-05 14:42 351 查看
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.



题目考察深度优先遍历,给出了DFS算法

class Solution {
public:
vector<string> letterCombinations(string digits) {

vector<string> ans;
if(digits.size() == 0)
return ans;

int depth = digits.size();
string tmp(depth, 0);
dfs(tmp, 0, depth, ans, digits);
return ans;
}

void dfs(string &tmp, int curdep, int depth, vector<string> &ans, string &digits){
if(curdep >= depth){
ans.push_back(tmp);
return ;
}
for(int i = 0; i < dic[digits[curdep] - '0'].size(); ++ i){
tmp[curdep] = dic[digits[curdep] - '0'][i];
dfs(tmp, curdep + 1, depth, ans, digits);
}
return ;
}
private:
string dic[10] = {{""},{""},{"abc"},{"def"},{"ghi"},{"jkl"},{"mno"},{"pqrs"},{"tuv"},{"wxyz"}};
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++