代码随想录算法训练营-Day23

题目

39. 组合总和

题解:

通过剩余多少和来进行递归条件、剪枝的判断

class Solution {
    List<List<Integer>> ans = new ArrayList<>();
    List<Integer> path = new ArrayList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        // 1. 必须排序,否则后面的剪枝 break 会导致漏解
        Arrays.sort(candidates); 
        dfs(candidates, target, 0);
        return ans;
    }

    private void dfs(int[] candidates, int remainSum, int startIdx) {
        if (remainSum == 0) {
            ans.add(new ArrayList<>(path));
            return;
        }

        // 循环从 startIdx 开始
        for (int i = startIdx; i < candidates.length; i++) {
            // 剪枝:因为排过序了,如果当前数都大了,后面的肯定更大,直接 break
            if (candidates[i] > remainSum) break;

            path.add(candidates[i]);

            // 【关键修改】这里传入 i,而不是 startIdx
            // 传入 i   -> 代表下一层还可以重复选当前这个 candidates[i]
            // 传入 i+1 -> 代表每个数只能用一次(那是组合总和 II 的逻辑)
            dfs(candidates, remainSum - candidates[i], i);
            
            path.remove(path.size() - 1); // 回溯
        }
    }
}
40. 组合总和Ⅱ

题解:

这题与上一题最大的区别在于,上一题是无重复元素的数组,而这一题是可以有重复元素的数组

虽然通过在调用dfs时令 startIdx=i+1 避免了重复使用同一个位置的元素,但没有避免在“同一层”使用数值相同的不同元素。

解决这个问题的核心口诀是:“树枝(纵向)可以重复,树层(横向)不能重复”。即,需要在for循环(横向)中进行去重。

class Solution {
    List<List<Integer>> ans = new ArrayList<>();
    List<Integer> path = new ArrayList<>();

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        // 1. 必须排序!去重逻辑依赖于相同的数字相邻
        Arrays.sort(candidates);
        dfs(candidates, target, 0);
        return ans;
    }

    private void dfs(int[] candidates, int remainSum, int startIdx) {
        if (remainSum == 0) {
            ans.add(new ArrayList<>(path));
            return;
        }

        for (int i = startIdx; i < candidates.length; i++) {
            // 剪枝:如果当前数字已经大于剩余和,后面的肯定更大,直接 break
            if (candidates[i] > remainSum) break;

            // 【核心去重逻辑】
            // i > startIdx:保证是当前层(横向)的第二个及以后的元素
            // candidates[i] == candidates[i-1]:保证和前一个数值相同
            if (i > startIdx && candidates[i] == candidates[i-1]) {
                continue;
            }

            path.add(candidates[i]);
            dfs(candidates, remainSum - candidates[i], i + 1);
            path.removeLast();
        }
    }
}
131. 分割回文串

题解:

分割问题(Partitioning)本质上就是组合问题的一种变形。

在组合问题中,通过 startIndex 和循环变量 i 来决定选取哪个数字。 在分割问题中,通过 startIndex 和循环变量 i 来决定在哪里切一刀(即截取哪一段子串)。

  • 组合问题:循环 i 遍历剩下的数字,选一个加入集合。
  • 分割问题:循环 i 遍历剩下的字符位置,[startIndex, i] 这一段就是本次尝试截取的子串。
class Solution {
    List<List<String>> ans = new ArrayList<>();
    List<String> path = new ArrayList<>();

    public List<List<String>> partition(String s) {
        dfs(s, 0);
        return ans;
    }

    private void dfs(String s, int startIdx) {
        // 1. 终止条件:切割线切到了字符串最后,说明切完了
        if (startIdx >= s.length()) {
            ans.add(new ArrayList<>(path));
            return;
        }

        // 2. 单层搜索逻辑
        // i 代表当前子串的【结束位置】
        // 所以当前尝试截取的子串范围是 [startIdx, i]
        for (int i = startIdx; i < s.length(); i++) {
            
            // 【关键点】判断截取下来的这一段 [startIdx, i] 是否是回文
            if (isPalindrome(s, startIdx, i)) {
                
                // 如果是回文,就放入 path
                String sub = s.substring(startIdx, i + 1);
                path.add(sub);
                
                // 递归:切割线跳到 i + 1
                dfs(s, i + 1);
                
                // 回溯
                path.removeLast();
                
            } else {
                // 如果这一段不是回文,那这一刀就不能切在这里
                // continue 继续尝试 i 往后移,看切长一点是不是回文
                continue;
            }
        }
    }

    // 辅助函数:双指针判断是否回文
    private boolean isPalindrome(String s, int start, int end) {
        while (start < end) {
            if (s.charAt(start) != s.charAt(end)) {
                return false;
            }
            start++;
            end--;
        }
        return true;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值