Leetcodes Solutions 17 Letter Combinations of a Phone Number

匯總

雪之下雪乃:leetcode解題總匯?

zhuanlan.zhihu.com圖標

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.

思路1

用一張表存儲數字對應的字元串。然後用分步乘法原理。利用一個tempres來保存當前的排列。

class Solution{public: vector<string> letterCombinations(string digits){ vector<string> res; if (digits.size() == 0) return res; string charmap[10] = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; res.push_back(""); for(int i =0; i < digits.size(); i++){ vector<string> tempres; string chars = charmap[digits[i] - 0]; for(int c = 0; c < chars.size(); c++) for(int j = 0; j < res.size(); j++) tempres.push_back(res[j] + chars[c]); res = tempres; } return res; }};

推薦閱讀:

個人的努力在時代的進步面前不值一提
關於在坐標系中旋轉平移物體的理論基礎解析
使用 simpler-paper 快速搭建文檔系統指南
Tumblr:我們是如何從 PHP 5 升級到 PHP 7 的
用ASP.NET MVC5 +SQLSERVER2014搭建多層架構的資料庫管理系統

TAG:編程 | 演算法 | 數據結構 |