回溯day2

39. 组合总和

class Solution {
    List<List<Integer>> res;
    LinkedList<Integer> path;
    int sum;
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        res = new ArrayList<>();
        path = new LinkedList<>();
        sum = 0;
        //需要排序,否则值小的数无法进入解空间
        Arrays.sort(candidates);
        backtracking(candidates, target, 0);
        return res;
    }
    private void backtracking(int [] candidates, int target, int s) {
        if (sum == target) {
            res.add(new ArrayList<>(path));
            return;
        }
        //剪枝 大于即将成为sum值大于target就没必要继续了
        for (; s < candidates.length && sum + candidates[s] <= target; s++) {
            path.add(candidates[s]);
            sum += candidates[s];
            backtracking(candidates, target, s);
            path.removeLast();
            sum -= candidates[s];
        }
    }
}

17. 电话号码的字母组合

class Solution {
    private List<String> res;
    private StringBuilder path;

    public List<String> letterCombinations(String digits) {
        res = new ArrayList<>();
        if (digits == null || digits.equals("")) return res;
        path = new StringBuilder();
        //存入需要操作的
        String[] reflect = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        List<String> need = new ArrayList<>();
        for (int c : digits.toCharArray()) {
            //排除输入1#*
            if (c >= '2' || c <= '9') 
                need.add(reflect[c - '2']);
        }
        backtracking(need, 0);
        return res;
    }

    private void backtracking(List<String> need, int i) {
        if (path.length() == need.size()) {
            res.add(new String(path));
            return;
        }
        for (char c : need.get(i).toCharArray()) {
            path.append(c);
            backtracking(need, i + 1);
            path.deleteCharAt(path.length() - 1);
        }
    }
}

参考:programmercarl.com

posted @   一梦两三年13  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
点击右上角即可分享
微信分享提示