17-电话号码字母的组合

 

 可以看出,假如输入的有两个数字,得用两层循环得出结果。假如输入三个数字,就得是三层循环。可以用递归

class Solution {//递归,
     public List<String> letterCombinations(String digits) {
        List<String> list = new ArrayList<>();//结果集合
        if (digits.equals("") || digits == null) {//假如输入为空,或者长度为0,直接返回list
            return list;
        }
        String now_str = "";//其中一个可能的字母组合。
        addNum(digits, 0, list, now_str);
        return list;
    }                            //参数意思分别是1:输入。2:下标,代表当前的数字是输入里的哪个。输入“2,3”,key为1,代表的就是“3”这个数字(字符) 3:最终的结果集合。4:其中一个可能的字母组合
 private static void addNum(String digits, int key, List<String> list, String now_str) {
        if (key == digits.length()) {//digits的下标是【0,digits.length()-1】,如果等于digits的长度了,说明已经得出了其中一个集合。把这个集合加入list,返回就行,
            list.add(now_str);
            return;
        }
        char[] values = getValue(digits.charAt(key));//比如输入是“23”,当前key为0,这个函数返回的就是2代表的字符数组,a,b,c
        for (int i = 0; i < values.length; i++) {//这次循环,把当前的数字,比如“2”所代表的字符a,b,c,加入可能的字母组合里面。
            addNum(digits, key + 1, list, now_str + values[i]);//假如这里now_str加了'a',在这个addNum函数里面,key变成1了,也就是“3”这个数字,可以想见,在循环里面,会逐个加入"3"代表的字符,组合成ad,ae,af之后都会加入list
        }
    }
    private static char[] getValue(char num) {//比如当前数字是2,取出2代表的字母的字符数组
        if (num == '2') {
            char nums[]= {'a', 'b', 'c'};
            return nums;
        } else if (num == '3') {
            char nums[]= {'d', 'e', 'f'};
            return nums;
        } else if (num == '4') {
            char nums[]= {'g', 'h', 'i'};
            return nums;
        } else if (num == '5') {
            char nums[]= {'j', 'k', 'l'};
            return nums;
        } else if (num == '6') {
            char nums[]= {'m', 'n', 'o'};
            return nums;
        } else if (num == '7') {
            char nums[]= {'p', 'q', 'r', 's'};
            return nums;
        } else if (num == '8') {
            char nums[]= {'t', 'u', 'v'};
            return nums;
        } else if (num == '9') {
            char nums[]= {'w', 'x', 'y', 'z'};
            return nums;
        }
        return null;
    }
}

  

posted @ 2020-04-22 16:08  弓呆的胖次  阅读(246)  评论(0编辑  收藏  举报