码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode17

时间:2019-04-20 21:34:16      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:ret   NPU   contain   nta   inpu   example   字母   new   oid   

17. Letter Combinations of a Phone Number
Medium
Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.

技术图片

Example:

Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

解答:

class Solution {
    public List<String> letterCombinations(String digits) {
        String[] table = new String[]{"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        List<String> list = new ArrayList<>();
        
        letterCombinations(list, digits, "", 0, table);
        
        return list;
    }
    
    private void letterCombinations(List<String> list, String digits, String curr, int index, String[] table) {
        // 最后一层退出条件
        if(index == digits.length()) {
            if(curr.length() != 0) {
                list.add(curr);
            }
            
            return;
        }
        
        String temp = table[digits.charAt(index)-‘0‘];
        
        for(int i = 0; i < temp.length(); i++) {
            String next = curr + temp.charAt(i);
            // 进入下一层
            letterCombinations(list, digits, next, index+1, table);
        }
    }
}

  

经典的backtracking(回溯算法)的题目。当一个题目,存在各种满足条件的组合,并且需要把它们全部列出来时,就可以考虑backtracking了。当然,backtracking在一定程度上属于穷举,所以当数据特别大的时候,不合适。而对于那些题目,可能就需要通过动态规划来完成。

  这道题的思路很简单,假设输入的是"23",2对应的是"abc",3对应的是"edf",那么我们在递归时,先确定2对应的其中一个字母(假设是a),然后进入下一层,穷举3对应的所有字母,并组合起来("ae","ad","af"),当"edf"穷举完后,返回上一层,更新字母b,再重新进入下一层。这个就是backtracing的基本思想。

 

https://www.cnblogs.com/kepuCS/p/5271654.html

leetcode17

标签:ret   NPU   contain   nta   inpu   example   字母   new   oid   

原文地址:https://www.cnblogs.com/wylwyl/p/10732572.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!