leetcode39-Combination Sum

题目

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。

candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。

对于给定的输入,保证和为 target 的不同组合数少于 150 个。

示例 1:

输入:candidates = [2,3,6,7], target = 7

输出:[[2,2,3],[7]]

解释:

2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。

7 也是一个候选, 7 = 7 。

仅有这两种组合。

分析

类似这种题目的套路一定是遍历数组+递归的解法,我们可以记录每次递归遍历到的下标,因为可以重复使用元素所以每次递归的时候需要考虑当前遍历到的元素,每次递归都用target-当前元素,递归结束的条件就是target=0的时候,但是如果target<0说明一系列元素累加起来不符合预期也可以结束递归

java 复制代码
import java.util.List;
import java.util.ArrayList;

public class combinationSum {
	private static List<Integer> cur = new ArrayList();
	private static List<List<Integer>> res = new ArrayList();

	public static void main(String[] args) {
		int[] arr = {2,3,6,7};
		getRes(arr,7,0);
		for(List<Integer> lis : res) {
			for(Integer num:lis) {
				System.out.print(num + " ");
			}
			System.out.println();
		}
	}
	public static void getRes(int[] arr,int target,int start) {
		if(target < 0) {
			return;
		}
		if(target == 0) {
			res.add(new ArrayList(cur));
			return;
		}
		for(int i = start;i<arr.length;i++) {
			cur.add(arr[i]);
			getRes(arr,target-arr[i],i);
			cur.remove(cur.size()-1);
		}
	}
}
相关推荐
君义_noip1 分钟前
信息学奥赛一本通 1615:【例 1】序列的第 k 个数
c++·算法·信息学奥赛·csp-s
ホロHoro1 分钟前
数据结构非线性部分(1)
java·数据结构·算法
Blossom.1185 分钟前
大模型推理优化实战:连续批处理与PagedAttention性能提升300%
大数据·人工智能·python·神经网络·算法·机器学习·php
沉下去,苦磨练!14 分钟前
实现二维数组反转
java·数据结构·算法
bybitq21 分钟前
Leetcode-3780-Python
python·算法·leetcode
桦说编程21 分钟前
实现一个简单的并发度控制执行器
java·后端·性能优化
如何原谅奋力过但无声22 分钟前
【力扣-Python-75】颜色分类(middle)
python·算法·leetcode
玖剹23 分钟前
哈希表相关题目
数据结构·c++·算法·leetcode·哈希算法·散列表
红豆诗人27 分钟前
数据结构初阶知识--单链表
c语言·数据结构
Spring AI学习30 分钟前
Spring AI深度解析(11/50):异常处理与容错机制实战
java·人工智能·spring