电话号码的字母组合

长度最大为4,所以用暴搜就好了,先将数字对应的字符串存储下来。用回溯写就好了。

class Solution {
    string maps[10]={"","","abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    void dfs(int u,string&path,vector<string>&ans,string &digits)
    {
        if(u==digits.length())
        {
            ans.push_back(path);
            return;
        }
        for(char c:maps[digits[u]-'0'])
        {
            path[u]=c;
            dfs(u+1,path,ans,digits);
        }
    }
public:
    vector<string> letterCombinations(string digits) {
        int n=digits.length();
        if(n==0)return{};
        vector<string>ans;
        string path(n,0);
        dfs(0,path,ans,digits);
        return ans;

    }
};

以下是一个使用 Java 实现电话号码字母组合的代码示例,思路一般是使用回溯算法来解决该问题。回溯算法通过递归的方式尝试所有可能的组合。 ```java import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class LetterCombinationsOfPhoneNumber { public List<String> letterCombinations(String digits) { List<String> res = new ArrayList<>(); if (digits == null || digits.length() == 0) { return res; } // 构建数字到字母的映射 Map<Character, String> phoneMap = new HashMap<>(); phoneMap.put('2', "abc"); phoneMap.put('3', "def"); phoneMap.put('4', "ghi"); phoneMap.put('5', "jkl"); phoneMap.put('6', "mno"); phoneMap.put('7', "pqrs"); phoneMap.put('8', "tuv"); phoneMap.put('9', "wxyz"); StringBuilder combation = new StringBuilder(); backtrack(res, phoneMap, digits, 0, combation); return res; } private void backtrack(List<String> res, Map<Character, String> phoneMap, String digits, int index, StringBuilder combation) { if (index == digits.length()) { res.add(combation.toString()); return; } char digit = digits.charAt(index); String letters = phoneMap.get(digit); int lettersCount = letters.length(); for (int i = 0; i < lettersCount; i++) { combation.append(letters.charAt(i)); backtrack(res, phoneMap, digits, index + 1, combation); combation.deleteCharAt(combation.length() - 1); } } public static void main(String[] args) { LetterCombinationsOfPhoneNumber solution = new LetterCombinationsOfPhoneNumber(); String digits = "23"; List<String> result = solution.letterCombinations(digits); System.out.println(result); } } ``` ### 解决方案说明 1. **构建映射**:首先创建一个 `Map` 来存储数字到字母的映射关系,例如数字 `2` 对应字母 `"abc"`。 2. **回溯函数**:定义一个回溯函数 `backtrack`,该函数接收当前组合结果列表、数字字母映射、输入的数字字符串、当前处理的数字索引和当前组合的字符串构建器作为参数。 3. **递归调用**:在回溯函数中,当处理完所有数字时,将当前组合添加到结果列表中。否则,获取当前数字对应的字母列表,遍历该列表,将每个字母添加到当前组合中,然后递归调用回溯函数处理下一个数字,最后移除刚刚添加的字母以进行下一次尝试。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值