2015年4月5日星期日

Letter Combinations of a Phone Numb leetcode

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.
Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

解题思路: 依旧用dfs 模型 把所有字母放入一个string array里
1. 返回条件: 当所得到的string长度与给入的string digits长度相同时候

public class Solution {
    public ArrayList<String> letterCombinations(String digits) {
        ArrayList<String> result = new ArrayList<String>();
        String[] map = {" ", " ", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        StringBuilder tem = new StringBuilder();
        if (digits.length() == 0){
            return result;
        }
        dfs(result, map, digits, tem, 0);
        return result;
    }
    public void dfs(ArrayList<String> result, String[] map, String digits, StringBuilder tem, int n){
        if (n == digits.length()){
            result.add(tem.toString());
            return;
        }
        String s = map[digits.charAt(n) - '0'];
        for (int i = 0; i < s.length(); i++){
            tem.append(s.charAt(i));
            dfs(result, map, digits, tem, n + 1);
            tem.deleteCharAt(tem.length() - 1);
        }
    }
}
注意:i < s.length( )
StringBuilder:
add: StringBuilder.append()
remove: StringBuilder.deleteCharAt(index)

String[i] : String.charAt(i)
digits.charAt(n) - '0' 是把字符串变成int

没有评论:

发表评论