代码随想录day27|

39. 组合总和

39. 组合总和

List<List<Integer>> result = new ArrayList<List<Integer>>();
LinkedList<Integer> path = new LinkedList<Integer>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
    backTracking(candidates, target, 0, 0);
    return result;
}
void backTracking(int[] candidates, int target, int sum, int startIndex){
    if(sum > target){
        return;
    }else if(sum == target){
        result.add(new ArrayList<Integer>(path));
        return;
    }

    for(int i = startIndex; i < candidates.length; i++){
        path.add(candidates[i]);
        sum += candidates[i];
        backTracking(candidates, target, sum, i);
        sum -= candidates[i];
        path.pollLast();
    }
    return;
}

40. 组合总和 II

40. 组合总和 II
LinkedList<Integer> path = new LinkedList<>();
List<List<Integer>> result = new ArrayList<List<Integer>>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
    Arrays.sort(candidates);
    int[] used = new int[candidates.length];
    backTracking(candidates, target, 0, 0, used);
    return result;
}
void backTracking(int[] nums, int target, int sum, int startIndex, int[] used){
    if(sum > target){
        return;
    }
    if(sum == target){
        result.add(new ArrayList<Integer>(path));
        return;
    }
    for(int i = startIndex; i < nums.length; i++){
        if(i > 0 && nums[i] == nums[i - 1] && used[i - 1] == 0){
            continue;
        }
        path.add(nums[i]);
        sum += nums[i];
        used[i] = 1;
        backTracking(nums, target, sum, i + 1, used);
        path.pollLast();
        sum -= nums[i];
        used[i] = 0;
    }

    return;
} 

131. 分割回文串

131. 分割回文串

private final List<List<String>> ans = new ArrayList<>();
private final List<String> path = new ArrayList<>();
private String s;
public List<List<String>> partition(String s) {
    this.s = s;
    dfs(0);
    return ans;
}

private boolean isValid(int left, int right){
    while(left < right){
        if(s.charAt(left++) != s.charAt(right--))
            return false;
    }
    return true;
}

private void dfs(int i){
    if(i == s.length()){
        ans.add(new ArrayList<>(path));
        return;
    }
    for(int j = i; j < s.length(); j++){
        if(isValid(i, j)){
            path.add(s.substring(i, j + 1));
            dfs(j + 1);
            path.remove(path.size() - 1);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值