[LeetCode]017. 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.
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.
Solution:
use a recursion method.
Running Time: O(n*m), n is the length of the number, m is the size of characters in keyboard(at most 4);
Note: watch the line 29, must delete the last char in sb for starting a new iteration, or the sb will add redundant characters.
such like this:
Input:"2"
Output:["a","ab","abc"]
Expected:["a","b","c"]
public class Solution {
    private String[] keyboard = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
    public ArrayList<String> letterCombinations(String digits) {
        // Start typing your Java solution below
        // DO NOT write main() function
        ArrayList<String> result = new ArrayList<String>();
        if(digits == null){
            return result;
        }
        if(digits.length() ==0){
            result.add("");
            return result;
        }
        StringBuffer sb = new StringBuffer();
        letterCombine(digits, sb, result, 0);
        return result;
    }
    
    private void letterCombine(String digits, StringBuffer sb, ArrayList<String> result, int i){
        if(i == digits.length()){
            result.add(sb.toString());
        }else{
            int index = digits.charAt(i) - '0';
            int size = keyboard[index].length();
            for(int j=0; j<size; j++){
                sb.append(keyboard[index].charAt(j));
                letterCombine(digits, sb, result, i+1);
                sb.deleteCharAt(sb.length()-1);
                //must delete the last char in sb to start a new iteration.
            }
        }
    }
}