组合总和ⅠⅡ(回溯算法)附框架

Leetcode39:组合总和Ⅰ

同类型题目:
括号生成问题

题目描述

在这里插入图片描述

思路图解

假设candidates = [2, 3, 6, 7],target = 7
以 target = 7 为根结点,每一个分支做减法。减到 0 或者负数的时候,剪枝。其中,减到 0 的时候结算,这里 “结算” 的意思是添加到结果集。
在这里插入图片描述

代码实现

package LeetCode;

import java.util.ArrayList;
import java.util.List;

/*
		 * 给定一个无重复元素的数组 candidates 和一个目标数 target ,
		找出 candidates 中所有可以使数字和为 target 的组合。
		candidates 中的数字可以无限制重复被选取。
		
		说明:
		所有数字(包括 target)都是正整数。
		解集不能包含重复的组合。 
		
		示例 1:
		输入: candidates = [2,3,6,7], target = 7,
		所求解集为:
		[
		  [7],
		  [2,2,3]
		]
		
		示例 2:
		输入: candidates = [2,3,5], target = 8,
		所求解集为:
		[
		  [2,2,2,2],
		  [2,3,3],
		  [3,5]
		]

*/
public class CombinationSum
{

	public static void main(String[] args)
	{
		int target=7;
		int[] nums= {2,3,6,7};
		System.out.println(combinationSum(nums, target));

	}
	 public static List<List<Integer>> combinationSum(int[] candidates,int target)
	 {
		 List<List<Integer>> res=new ArrayList<List<Integer>>();
		 if (candidates==null||candidates.length==0)return res;
		 helper(res, new ArrayList<Integer>(), candidates, target, 0);
		 
		return res;
		 
	 }
	 public static void helper(List<List<Integer>> res,List<Integer> list,int[]candidates,int target,int start)
	 {
		 if (target<0) return;
		 if (target==0)
		{
			res.add(new ArrayList<Integer>(list));
			return;
		}
		 for (int i = start; i < candidates.length; i++)
		{
			list.add(candidates[i]);
			// 【关键】因为元素可以重复使用,这里递归传递下去的是 i 而不是 i + 1
			helper(res, list, candidates, target-candidates[i], i);
			list.remove(list.size()-1);
		}
	 }
}

运行结果

在这里插入图片描述

Leetcode40:组合总和Ⅱ

题目描述

在这里插入图片描述在这里插入图片描述

思路图解

以 target 为根结点,依次减去数组中的数字,直到小于0或者等于 0,把等于0的结果记录到结果集中。
在这里插入图片描述

代码实现

package LeetCode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CombinationSum2
{

	public static void main(String[] args)
	{
		int[] candidates ={2, 5, 2, 1, 2};
		int target = 5;
		System.out.println(combinationSum2(candidates, target));
	}

	public static List<List<Integer>> combinationSum2(int[] candidates,
			int target)
	{
		List<List<Integer>> res = new ArrayList<List<Integer>>();
		if (candidates == null || candidates.length == 0)
			return res;
		Arrays.sort(candidates);
		helper(res, new ArrayList<>(), candidates, target, 0);

		return res;

	}

	/**
	 * 
	 * @param res        存放结果集的集合
	 * @param list       存放结果的集合
	 * @param candidates 候选数组
	 * @param target     目标值
	 * @param start      从候选数组的 start 位置开始搜索
	 */
	private static void helper(List<List<Integer>> res, List<Integer> list,
			int[] candidates, int target, int start)
	{
		if (target < 0)
			return;
		if (target == 0)
		{
			res.add(new ArrayList<Integer>(list));
			return;
		}
		for (int i = start; i < candidates.length; i++)
		{
			if (i != start && candidates[i] == candidates[i - 1])
				continue;
			list.add(candidates[i]);
			// 因为元素不可以重复使用,这里递归传递下去的是 i + 1 而不是 i
			helper(res, list, candidates, target - candidates[i], i + 1);
			list.remove(list.size() - 1);
		}

	}
}

运行结果

在这里插入图片描述

【回溯框架总结】重要*8

解决一个回溯问题,实际上就是一个决策树的遍历过程。你只需要思考 3 个问题:

  1. 路径:也就是已经做出的选择。
  2. 选择列表:也就是你当前可以做的选择。
  3. 结束条件:也就是到达决策树底层,无法再做选择的条件。

代码方面,回溯算法的框架:

result = []
def backtrack(路径, 选择列表):
    if 满足结束条件:
        result.add(路径)
        return

for 选择 in 选择列表:
    做选择
    backtrack(路径, 选择列表)
    撤销选择


其核心就是 for 循环里面的递归,在递归调用之前「做选择」,在递归调用之后「撤销选择」,特别简单。
在这里插入图片描述

发布了88 篇原创文章 · 获赞 27 · 访问量 5908

猜你喜欢

转载自blog.csdn.net/weixin_43362002/article/details/104107751