09.leetcode-17 Letter Combinations of a Phone Number(回溯法)

题目:

Letter Combinations of a Phone Number

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

示例:

输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

说明:
尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。

解题分析:

可以采用:回溯法;

由于要求所有的可能性,因此考虑使用回溯法进行求解。回溯是一种通过穷举所有可能情况来找到所有解的算法。如果一个候选解最后被发现并不是可行解,回溯算法会舍弃它,并在前面的一些步骤做出一些修改,并重新尝试找到可行解。究其本质,其实就是枚举。

如果没有更多的数字需要被输入,说明当前的组合已经产生。

如果还有数字需要被输入:

  • 遍历下一个数字所对应的所有映射的字母

  • 将当前的字母添加到组合最后;

时间复杂度:O(2^n)

class Solution{

     private String letterMap[] = {
            "",    //0
            "",     //1
            "abc",  //2
            "def",  //3
            "ghi",  //4
            "jkl",  //5
            "mno",  //6
            "pqrs", //7
            "tuv",  //8
            "wxyz"  //9
    };

    private ArrayList<String> result;

    public List<String> letterCombinations(String digits){

        result = new ArrayList<String>();

        // 如果为空串,直接返回
        if(digits.length() == 0){
            return result;
        }

        dfs(digits, 0, "");
        return result;

    }

    public void dfs(String digits, int index, String s){
        // 数字取完了,就开始添加组合字母
        if(index == digits.length()){
            result.add(s);
            return;
        }

        // 获取当前数字
        Character c = digits.charAt(index);

        // 获取数字对应的字母映射
        String letters = letterMap[c - '0'];
        
        // 对获取到的字母映射进行遍历,与其他字母映射进行组合
        for(int i = 0; i < letters.length(); i ++){
            dfs(digits, index + 1, s + letters.charAt(i));
        }
    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值