美文网首页
Letter Combinations of a Phone N

Letter Combinations of a Phone N

作者: 走地牙 | 来源:发表于2018-07-12 04:47 被阅读0次

    //本题用dfs的思路解题;

    class Solution { public ListletterCombinations(String digits) { //建立list 收集结果用 List resultList = new ArrayList<>();

            //判断是否为空

            if(digits == null || digits.length() == 0) return resultList;

            //建立一个具有映射关系的string数组

            String[] myMap = new String[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };

            //建立一个list 放入 映射过来的string; List digitToString = new ArrayList<>();

            for(char c : digits.toCharArray()) {

                digitToString.add(myMap[c - '0']);

            }

            int start = 0;

            StringBuilder result = new StringBuilder();

            helper(start, digitToString, resultList, result);

            return resultList;

        }

    private void helper(int start, ListdigitToString, List resultList, StringBuilder result) {

            if(start == digitToString.size()) {

                resultList.add(result.toString());

                return;

            }

            for(int i = 0; i < digitToString.get(start).length(); i++) {

                result.append(digitToString.get(start).charAt(i));

                helper(start + 1, digitToString, resultList, result);

                result.deleteCharAt(result.length() - 1);

            }

        }

    }

    相关文章

      网友评论

          本文标题:Letter Combinations of a Phone N

          本文链接:https://www.haomeiwen.com/subject/lrflpftx.html