【刷题day27】回溯算法 | 39. 组合总和、40.组合总和II、131.分割回文串

39. 组合总和

class Solution {
	private List<List<Integer>> ans = new ArrayList<List<Integer>>();
	private List<Integer> path = new ArrayList<Integer>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
    	backTracking(candidates, target, 0, 0);
    	return ans;
    }
    private void backTracking(int[] candidates, int target, int sum, int startIndex) {
    	if(sum > target) return;
    	if(sum == target) {
    		ans.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); //注意下一层的遍历从i开始,因为可以重复
    		sum -= candidates[i];
    		path.remove(path.size() - 1);
    	}
    }
}

剪枝优化 :对于sum已经大于target的情况,代码会依然进入了下一层递归,只是下一层递归结束判断的时候,会判断sum > target的话就返回。其实,如果已经知道下一层的sum会大于target,就没有必要进入下一层递归了。那么可以在for循环的搜索范围上做做文章了。对总集合排序之后,如果下一层的sum(就是本层的 sum + candidates[i])已经大于target,就可以结束本轮for循环的遍历。

class Solution {
	private List<List<Integer>> ans = new ArrayList<List<Integer>>();
	private List<Integer> path = new ArrayList<Integer>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates); // 先进行排序
    	backTracking(candidates, target, 0, 0);
    	return ans;
    }
    private void backTracking(int[] candidates, int target, int sum, int startIndex) {
    	// if(sum > target) return; //无需再进入递归判断
    	if(sum == target) {
    		ans.add(new ArrayList<Integer>(path));
    		return;
    	}
    	for(int i = startIndex; i < candidates.length; i++) {
            sum += candidates[i];
            if(sum > target) break; //下一层的sum大于target,由于已经排序好了,就没有必要进入下一层递归了
    		path.add(candidates[i]);
    		backTracking(candidates, target, sum, i); //注意下一层的遍历从i开始,因为可以重复
    		path.remove(path.size() - 1);
            sum -= candidates[i];
    	}
    }
}

40. 组合总和II

思路: 和上题相似,注意上题的 candidates 数组是没有重复元素的。本题的难点在于集合(数组candidates)有重复元素,但结果集中不能有重复的组合,故本题的去重是关键。

  • 组合问题可以抽象为树形结构,那么“使用过”在这个树形结构上是有两个维度的,一个维度是同一树枝上使用过,一个维度是同一树层上使用过。那么问题来了,我们是要同一树层上使用过,还是同一树枝上使用过呢?

    回看一下题目,元素在同一个组合内是可以重复的,怎么重复都没事,但两个组合不能相同。所以我们要去重的是同一树层上的“使用过”,同一树枝上的都是一个组合里的元素,不用去重。

1. 使用used标记数组去重
为了理解去重我们来举一个例子,candidates = [1, 1, 2], target = 3,(方便起见candidates已经排序了)
强调一下,树层去重的话,需要对数组排序!
选择过程树形结构如图所示:(增加了used数组)

如果candidates[i] == candidates[i - 1] 并且 used[i - 1] == false,就说明:前一个树枝,使用了candidates[i - 1],也就是说同一树层使用过candidates[i - 1]。此时for循环里就应该做continue的操作。为什么会这样呢?如图:

可以看出在 candidates[i] == candidates[i - 1] 的情况下:

  • used[i - 1] == true,说明同一树枝 candidates[i - 1] 使用过
  • used[i - 1] == false,说明同一树层 candidates[i - 1] 使用过

used[i - 1] == false 表示的是,当前取的 candidates[i] 是从 candidates[i - 1] 回溯而来的;
而 used[i - 1] == true,说明是进入下一层递归,去取下一个数,所以是树枝上。

class Solution {
	private List<List<Integer>> ans = new ArrayList<List<Integer>>();
	private List<Integer> path = new ArrayList<Integer>();
	private boolean[] used;
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
    	used = new boolean[candidates.length];
    	Arrays.fill(used, false); // 加标志数组,用来辅助判断同层节点是否已经遍历
        Arrays.sort(candidates); // 为了将重复的数字都放到一起,所以先进行排序
    	backTracking(candidates, target, 0, 0);
    	return ans;
    }
	private void backTracking(int[] candidates, int target, int sum, int startIndex) {
		if(sum == target) {
			ans.add(new ArrayList<Integer>(path));
			return;
		}
		for(int i = startIndex; i < candidates.length; i++) {
			if(sum + candidates[i] > target) break;
		    if (i > 0 && candidates[i] == candidates[i - 1] && !used[i - 1]) continue;
		    used[i] = true; 
			path.add(candidates[i]);
			backTracking(candidates, target, sum + candidates[i], i + 1);
			path.remove(path.size() - 1);
            used[i] = false; // 注意回溯完的标记改变
		}
	}
}

2. 使用startIndex进行去重

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

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates); // 为了将重复的数字都放到一起,所以先进行排序
    	backTracking(candidates, target, 0, 0);
    	return ans;
    }
	private void backTracking(int[] candidates, int target, int sum, int startIndex) {
		if(sum == target) {
			ans.add(new ArrayList<Integer>(path));
			return;
		}
		for(int i = startIndex; i < candidates.length; i++) {
			if(sum + candidates[i] > target) break;
		    if (i > startIndex && candidates[i] == candidates[i - 1]) continue; // 注意此处对树结构同一层的重复元素进行去重,上下层的重复元素不受影响,关键在于i > startIndex
			path.add(candidates[i]);
			backTracking(candidates, target, sum + candidates[i], i + 1);
			path.remove(path.size() - 1);
		}
	}
}

3. 使用set去重

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

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates); // 为了将重复的数字都放到一起,所以先进行排序
    	backTracking(candidates, target, 0, 0);
    	return ans;
    }
	private void backTracking(int[] candidates, int target, int sum, int startIndex) {
		if(sum == target) {
			ans.add(new ArrayList<Integer>(path));
			return;
		}
        Set<Integer> set = new HashSet<Integer>();
		for(int i = startIndex; i < candidates.length; i++) {
			if(sum + candidates[i] > target) break;
		    if (set.contains(candidates[i])) continue;
            set.add(candidates[i]);
			path.add(candidates[i]);
			backTracking(candidates, target, sum + candidates[i], i + 1);
			path.remove(path.size() - 1);
		}
	}
}

131. 分割回文串

在这里插入图片描述

class Solution {
	private List<List<String>> ans = new ArrayList<List<String>>();
	private Deque<String> path = new LinkedList<String>(); // 方便删除最后的元素进行回溯
    public List<List<String>> partition(String s) {
    	backTracking(s, 0);
    	return ans;
    }
    private void backTracking(String s, int startIndex) {
    	if(startIndex >= s.length()) {
    		ans.add(new ArrayList(path));
    		return;
    	}
    	for(int i = startIndex; i < s.length(); i++) {
    		if(isPalindrome(s.substring(startIndex, i + 1))) {
    			path.add(s.substring(startIndex, i + 1));
    		}else {
				continue;
			}
    		backTracking(s, i + 1);
    		path.removeLast();
    	}
    }
    private boolean isPalindrome(String s) { // 判断回文串
    	int left = 0, right = s.length() - 1;
    	while(left < right) {
    		if(s.charAt(left) != s.charAt(right)) return false;
            left++;
            right--;
    	}
    	return true;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值