首页 > 其他分享 >【LeetCode】电话号码的字母组合

【LeetCode】电话号码的字母组合

时间:2023-02-16 21:12:55浏览次数:44  
标签:digits tmp str res 电话号码 字母组合 LeetCode string

电话号码的字母组合

题目

给定一个仅包含数字 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 <= 4
digits[i] 是范围 ['2', '9'] 的一个数字。

思路

深度优先遍历

class Solution {
public:
    string map[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    vector<string> res; // 用来保存结果
    string tmp; // 用来保存每个分支
    vector<string> letterCombinations(string digits) {
        if(digits.size() == 0) return res;
        dfs(digits, 0);
        return res;
    }

    void dfs(string &str, int i) {
        if (i == str.size()){ // 遍历到头了,将tmp存入res中,然后返回上一级
            res.push_back(tmp);
            return;
        }
        for (int j = 0; j < map[str[i] - '0'].size(); j++) {
            tmp += map[str[i] - '0'][j];
            // 遍历下一个字符
            dfs(str, i + 1);
            tmp.pop_back();
        }
    }
};

标签:digits,tmp,str,res,电话号码,字母组合,LeetCode,string
From: https://www.cnblogs.com/basilicata/p/17128250.html

相关文章

  • 【LeetCode】三数之和
    三数之和题目描述给你一个整数数组nums,判断是否存在三元组[nums[i],nums[j],nums[k]]满足i!=j、i!=k且j!=k,同时还满足nums[i]+nums[j]+nums[k]==......
  • 【LeetCode】15. 三数之和
    classSolution{public:vector<vector<int>>threeSum(vector<int>&nums){vector<vector<int>>result;sort(nums.begin(),nums.end());......
  • 代码随想录算法训练营day22 | leetcode 235. 二叉搜索树的最近公共祖先 ● 701.二叉
    LeetCode235.二叉搜索树的最近公共祖先分析1.0 二叉搜索树根节点元素值大小介于子树之间,所以只要找到第一个介于他俩之间的节点就行classSolution{publicTre......
  • [LeetCode] 2341. Maximum Number of Pairs in Array
    Youaregivena 0-indexed integerarray nums.Inoneoperation,youmaydothefollowing:Choose two integersin nums thatare equal.Removebothinte......
  • leetcode 11. 盛最多水的容器 js实现
    给定一个长度为n的整数数组 height 。有 n 条垂线,第i条线的两个端点是 (i,0) 和 (i,height[i]) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容......
  • Leetcode736 Lisp语法解析
      解法主要有两项工作:1、处理作用域(栈或递归);2、顺序处理逻辑:(1)根据分隔符将语句拆解为token;(2)根据关键字的运算逻辑定义状态,设计自动机;(3)从左至右逐个解析......
  • 【算法训练营day45】LeetCode70. 爬楼梯(进阶) LeetCode322. 零钱兑换 LeetCode279. 完
    LeetCode70.爬楼梯(进阶)题目链接:70.爬楼梯(进阶)独上高楼,望尽天涯路可以把爬楼梯看成是一个排序问题加完全背包。classSolution{public:intclimbStairs(intn)......
  • leetcode-1365-easy
    HowManyNumbersAreSmallerThantheCurrentNumberGiventhearraynums,foreachnums[i]findouthowmanynumbersinthearrayaresmallerthanit.Thatis......
  • leetcode-1374-easy
    GenerateaStringWithCharactersThatHaveOddCountsGivenanintegern,returnastringwithncharacterssuchthateachcharacterinsuchstringoccursan......
  • leetcode-1051-easy
    HeightCheckerAschoolistryingtotakeanannualphotoofallthestudents.Thestudentsareaskedtostandinasinglefilelineinnon-decreasingorderby......