首页 > 其他 > 详细

17. 电话号码的字母组合

时间:2019-08-17 12:58:24      阅读:101      评论:0      收藏:0      [点我收藏+]

技术分享图片
递归

class Solution {
    List<String> ls;
    String[] arr = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };

    public List<String> letterCombinations(String digits) {
        ls = new ArrayList<String>();
        ls.clear();
        if (digits != null && digits.length() > 0)
            dfs( digits, "");
        return ls;
    }

    public void dfs( String num, String res) {
        if (num.length() == 0)
            ls.add(res);
        else {
            int flag = num.charAt(0) - '0';
            for (int i = 0; i < arr[flag].length(); i++) {
                dfs( num.substring(1), res + arr[flag].charAt(i));
            }
        }
    }
}

循环

class Solution {

    String[] arr = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };

    public List<String> letterCombinations(String digits) {
        List<String> ls = new ArrayList<String>();
        ls.clear();
        if (digits != null && digits.length() > 0) {
            ls.add("");
            for(int i = 0 ; i < digits.length() ;i++) {
                List<String> temp = new ArrayList<String>();
                for(int x = 0 ; x < arr[digits.charAt(i)-'0'].length() ;x++) {
                    for(String y : ls) {
                        temp.add(y+arr[digits.charAt(i)-'0'].charAt(x));
                    }
                }
                ls = temp;
            }
        }
        return ls;
    }
}

17. 电话号码的字母组合

原文:https://www.cnblogs.com/cznczai/p/11367653.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!