17. Letter Combinations of a Phone Number

来源:互联网 发布:mysql5.7数据库安装 编辑:程序博客网 时间:2024/06/05 15:38

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.

这道题可以用迭代法,维护一个vector<string> ans ,在每一轮迭代中更新ans(在ans的每一个string后添加该数字对应的字母),最后得到所有的字母组合。

class Solution {public:    vector<string> letterCombinations(string digits) {        vector<string> ans;        if (digits.empty()) return ans;        ans.push_back("");        string charMap[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};        for (int i = 0; i < digits.size(); i++) {            vector<string> tmp;            string str = charMap[digits[i] - '2'];            for (int j = 0; j < str.size(); j++) {                for (int k = 0; k < ans.size(); k++) {                    tmp.push_back(ans[k] + str[j]);                }            }            ans = tmp;        }        return ans;    }};