0
点赞
收藏
分享

微信扫一扫

Welcome to nginx!怎么解决?

分湖芝蘭 2024-04-29 阅读 19

Day27题目

LeetCode39组合总和

核心思想:经典回溯

class Solution {
    int sum = 0;
    //记录当前元素
    List<Integer> path = new ArrayList<>();
    // 记录返回值
    List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        help(candidates,0,target);
        return res;
    }
    public void help(int[] candidates,int start,int target){
        // 返回条件是sum 大于target,这样就不能再有和等于target,因为元素全部是正数
        if(sum > target) return;
        for(int i = start ; i < candidates.length; i ++){
            sum = sum + candidates[i];
            path.add(candidates[i]);
            if(sum == target){
                res.add(new ArrayList(path));
            }else{
                help(candidates,i,target);
            }
            // 回溯
            sum = sum-candidates[i];
            path.removeLast();
        }
    }
}

LeetCode40组合总和Ⅱ:多了去重

核心思想:主要是去重部分:去重有好几种方法:使用Boolean数组,set,排序后比较是否和前一个元素相同

class Solution {
    List<Integer> path = new ArrayList<>();
    List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        // 不使用used 数组
        Arrays.sort(candidates);
        help(candidates,target,0,0);
        return res;
    }
    public void help(int[] candidates, int target, int start, int sum){
        if(sum > target) return;
        if(sum == target) {
            res.add(new ArrayList(path));
        }
        // 这里做了剪枝  4ms->2ms
        for(int i = start; i < candidates.length && sum+candidates[i] <= target ;i ++){
        	// 这里是在层部分判断是否是和前一个相同。 i>start 则表示是同一层
            if(i > start && candidates[i-1] == candidates[i]) continue;
            path.add(candidates[i]);
            help(candidates,target,i+1,sum+candidates[i]);
            path.removeLast();
        }
    }
}

LeetCode131.分割回文串

核心思想:使用start维护一个字符串的起始

class Solution {
    List<String> path = new ArrayList<>();
    List<List<String>> res = new ArrayList<>();
    public List<List<String>> partition(String s) {
        help(s,0);
        return res;
    }
    public void help(String s,int start){
    	// 左闭右开
        if(start >= s.length()){
            res.add(new ArrayList(path));
            return;
        }
        // 从start 开始,可以切 1 -> s.length-start-1 种截取的方法。
        for(int i = start+1; i <= s.length();  i++ ){
            if(isReverse(s,start,i)){
                // 是回文串之后进行进一步遍历
                path.add(s.substring(start,i));
                help(s,i);
                path.removeLast();
            }
        }
    }
    public boolean isReverse(String s,int start,int end){
     for (int i = start, j = end-1; i < j; i++, j--) {
         if (s.charAt(i) != s.charAt(j)) {
             return false;
         }
     }
     return true;
    }
}
举报

相关推荐

0 条评论