LeetCode 134 Letter Combinations of a Phone Number

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.

LeetCode 134 Letter Combinations of a Phone Number_第1张图片

Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.

分析:

看到返回所有,应该想到回溯,即DFS。

public class Solution {
    public List<String> letterCombinations(String digits) {
        //存候选
        String[] ss = {" ", "", "abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        List<String> res = new ArrayList<String>();
        dfs(res, digits.length(), ss, digits, new StringBuffer());
        return res;
    }
    
    public void dfs(List<String> res, int remain, String[] ss, String digits, StringBuffer sb){
        if(remain==0){
            res.add(sb.toString());
            return;
        }
        String s = ss[digits.charAt(0)-'0'];
        //对所有情况进行处理
        for(int i=0; i<s.length(); i++){
            sb.append(s.charAt(i));
            dfs(res, remain-1, ss, digits.substring(1), sb);
            sb.deleteCharAt(sb.length()-1);
        }
    }
}


你可能感兴趣的:(LeetCode,letter,combinations)