Letter Combinations of a Phone Number

这道题也属于排列组合问题,所以用recursive。属于深度优先的题目。这道题和单纯的subset和permutation略有不同,因为是从不同数字代表的字母中选,而每个数字内部的组合不需要。 在想这道题的时候我们可以先想两个数字,就是从第一个的数字所代表的字母中依次选出,然后和下一个数字代表的字母组合。如果是三个也同理,所以首先确定肯定是recursive,然后开始考虑搜索模版。模版两个条件,第一个是什么时候加入结果,这道题其实就是当加入的字母组合长度和所给的digits长度相同。两二个不是for loop里面有什么条件,而是如何construct这个for loop。首先要拿到需要依次加入的数字对应的字母表。然后loop就是这个字母表的长度。

public class Solution {
    /**
     * @param digits A digital string
     * @return all posible letter combinations
     */
    public ArrayList<String> letterCombinations(String digits) {
        // Write your code here
        ArrayList<String> result = new ArrayList<String>();
        if("".equals(digits)){ //if it is null, it will return false. So no need to check null again
            return result;
        }
        String[] dic = {" ","", "abc", "def", "ghi", "jkl", "mno", "pqrs","tuv",
                        "wxyz"};
        StringBuilder s = new StringBuilder();
        helper(result, s, dic, digits, 0);
        return result;
    }
    
    private void helper(ArrayList<String> result, StringBuilder s, String[] dic,
                        String digits, int pos){
        if (digits.length() == pos){
            result.add(s.toString());
            return;
        }
        int num = digits.charAt(pos) - '0';
        for(int i = 0; i < dic[num].length(); i++){
            s.append(dic[num].charAt(i));
            helper(result, s, dic, digits, pos+1);
            s.deleteCharAt(s.length()-1);
        }
    }
    
}

有两个细节

1)如何拿到字母表,这道题是用digit char相减确定dic的index

2)当符合的条件组合找到,加入result以后,一定需要return,因为不然会继续执行语句, 其中digits.charAt(pos)会out of bound。

posted on 2016-08-19 06:55  codingEskimo  阅读(148)  评论(0编辑  收藏  举报

导航