Leetcode 17. Letter Combinations of a Phone Number

本文介绍了一个使用递归方法实现的算法,该算法可以根据输入的数字字符串返回所有可能的字母组合,这些字母对应于电话按键上的字母。通过一个映射数组和递归辅助函数实现了这一功能。

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

public class Solution {
    public List<String> letterCombinations(String digits) {
        String[] mapping = {"", "", "abc", "def", "ghi", "jkl", "mon", "pqrs", "tuv", "wxyz"};
        List<String> res = new ArrayList<>();
        if (digits == null || digits.length() == 0)
            return res;
        helper(0, digits, mapping, new StringBuilder(), res);
        return res;
    }
    /**
     * @param
     * i, index of current digit
     * digits, digits string
     * mapping, a map between digtis and letters
     * curr, a StringBuilde to save the path from first digit to last
     * res, result list
     */ 
    public void helper(int i, String digits, String[] mapping, StringBuilder curr, List<String> res) {
        if (i == digits.length()) {                         // reache the end of digits, save the path to the result list
            res.add(curr.toString());
            return;
        }
        String str = mapping[digits.charAt(i)-'0'];
        for (int k=0; k<str.length(); k++) {
            curr.append(str.charAt(k));                     // add current lettern to the path
            helper(i+1, digits, mapping, curr, res);        // move to next digit
            curr.setLength(curr.length()-1);                // finish a path, remove the previous letter from the StringBuilder
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值