首页 > 其他 > 详细

回溯法

时间:2021-05-05 21:33:50      阅读:23      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

leecode第17题

从上至下遍历每个节点,直至最深深度为方法出口,返回上一层,然后移除当前元素。

技术分享图片

 

 

public class test {
    public static void main(String[] args) {
        String s = "23";
        List<String> list = new test().solution(s);
        System.out.println(list);
    }

    private List<String> solution(String digits) {
        List<String> combinations = new ArrayList<>();
        if (digits.length() == 0) {
            return combinations;
        }

        Map<Character, String> phoneMap = new HashMap<Character, String>() {{
            put(‘2‘, "abc");
            put(‘3‘, "def");
            put(‘4‘, "ghi");
            put(‘5‘, "jkl");
            put(‘6‘, "mno");
            put(‘7‘, "pqrs");
            put(‘8‘, "tuv");
            put(‘9‘, "wxyz");
        }};

        int p = 0;
        StringBuilder sb = new StringBuilder();
        List result = exectorSolution(phoneMap, digits, combinations, p, sb);
        return result;


    }

    private List exectorSolution(Map<Character, String> phoneMap, String digits, List<String> combinations, int p, StringBuilder sb) {
        //若索引遍历到底后,递归方法结束
        if (digits.length() == p) {
            //达到最深,list中添加sb其中一种组合情况
            combinations.add(sb.toString());
        } else {
            String str = phoneMap.get(digits.charAt(p));
            //遍历当前深度对应的所有字符
            for (int i = 0; i < str.length(); i++) {
                sb.append(str.charAt(i));
                //回溯法,调用下一个节点深度的所有字符
                exectorSolution(phoneMap, digits, combinations, p + 1, sb);
                //结束后把当前的字符串从sb中移除
                sb.deleteCharAt(p);
            }

        }
        return combinations;
    }
}

 

回溯法

原文:https://www.cnblogs.com/chenfx/p/14732186.html

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