开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 3 天,点击查看活动详情
引言
算法的技能对于程序员是百益而无一害,作为程序员无论是前端还是后端算法技能对于我们都是十分十分的重要,我将陆续整理并讲解前端程序员必须掌握的经典算法。
题目描述
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例 1:
输入: digits = "23"
输出: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
示例 2:
输入: digits = ""
输出: []
示例 3:
输入: digits = "2"
输出: ["a","b","c"]
提示:
0 <= digits.length <= 4digits[i]是范围['2', '9']的一个数字。
分析
回溯算法类似于二叉树的先序遍历先序遍历先序遍历或者深度优先算法深度优先算法深度优先算法就是先一个劲的往前找,然后找到底以后再回退到上一层的后面一个继续往前找,这就是回溯算法。 以这道题为例:输入234234234,那就是先找adgadgadg,adhadhadh,adiadiadi,然后回到上一层的后面一个找aegaegaeg,aehaehaeh,aeiaeiaei 以此类推即可。
解答
public class Solution { public IList<string> LetterCombinations(string digits) { List<string> res = new List<string>(); if(digits.Length == 0) return res; Dictionary<char,string> dic = new Dictionary<char,string>(); dic.Add('2', "abc"); dic.Add('3', "def"); dic.Add('4', "ghi"); dic.Add('5', "jkl"); dic.Add('6', "mno"); dic.Add('7', "pqrs"); dic.Add('8', "tuv"); dic.Add('9', "wxyz"); Recall(0, "", digits, dic, res); return res; } public void Recall(int index, string str, string digits, Dictionary<char,string> dic, List<string> res) { if(str.Length == digits.Length) { res.Add(str); return; } string temp = dic[digits[index]]; for(int i = 0;i < temp.Length;i++) { str += temp[i]; Recall(index+1, str, digits, dic, res); str = str.Remove(str.Length - 1); } } }
总结
上面的算法思路让我学到了许多知识啊