17:Letter Combinations of a Phone Number(字母组合的电话号码)

本文介绍了一种将数字字符串转换为其所有可能的字母组合的算法。通过迭代方式,结合电话按键上的数字到字母映射,生成所有组合。适用于解决电话号码对应文字组合的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述
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”].

解题思路
该题目是要根据输入的数字,输出它们所代表的所有的字母的组合,而每个数字所代表的字母已知,如上图所示。这道题的思路相对来说比较清晰,我们可以采用迭代的方法,我们可以依次读入一位数字,然后将这位数字所代表的字母添加到我们的输出结果中,然后依次读下一位数字,直至完成。
代码展示

#include <iostream>
#include <stdlib.h>
#include <vector>
#include <string>
using namespace std; 

class Solution {
public:
    vector<string> letterCombinations(string digits) {
          vector<string> v;
          string s="";
          v.push_back(s);
           string d[8] = { "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};//数字代表的字母,2~9 
          for(int i = 0; i < digits.size(); ++ i)  //用循环依次读入数字的位数 
          {
             vector<string> temp;
             for(int j = 0; j < v.size(); ++ j)
                 for(int k = 0; k < d[digits[i] - '2'].size(); ++ k)
                     temp.push_back(v[j] + d[digits[i] - '2'][k]);   //将数字代表的字母添加到结果中 
             v = temp;
         }
         return v;
    }
};

int main(){
    string digits;
    cin>>digits;
    vector<string> result;
    Solution solution;
    result=solution.letterCombinations(digits);
     for(int i = 0; i < result.size(); ++ i){
        cout<<result[i]<<"  ";
     }
     cout<<endl;
}

运行结果展示
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值