|
|
@@ -0,0 +1,63 @@
|
|
|
+package leetcode.p39;
|
|
|
+
|
|
|
+import java.util.*;
|
|
|
+
|
|
|
+/**
|
|
|
+ * @ProjectName: LeetCode
|
|
|
+ * @FileName: Solution
|
|
|
+ * @Author: 杨逸
|
|
|
+ * @Data:2026/3/8 19:13
|
|
|
+ * @Description: https://leetcode.cn/problems/combination-sum/description/
|
|
|
+ * 39. 组合总和
|
|
|
+ */
|
|
|
+public class Solution {
|
|
|
+ /**
|
|
|
+ * 回溯法
|
|
|
+ * @param candidates
|
|
|
+ * @param target
|
|
|
+ * @return {@code List<List<Integer>> }
|
|
|
+ * @description:
|
|
|
+ * @author: 杨逸
|
|
|
+ * @data:2026/03/08 19:28:31
|
|
|
+ * @since 1.0.0
|
|
|
+ */
|
|
|
+ public List<List<Integer>> combinationSum(int[] candidates, int target) {
|
|
|
+ List<List<Integer>> result = new ArrayList<>();
|
|
|
+ //储存格式:元素个数-元素乘积
|
|
|
+ HashSet<String> set = new HashSet<>();
|
|
|
+ dfs(0,0,new LinkedList<>(),candidates,target,result);
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * @param index 当前遍历的元素下标
|
|
|
+ * @param current 当前元素的和
|
|
|
+ * @param deque 当前元素列表
|
|
|
+ * @param candidates 候选元素列表
|
|
|
+ * @param target 目标值
|
|
|
+ * @param result 结果列表
|
|
|
+ * @description:
|
|
|
+ * @author: 杨逸
|
|
|
+ * @data:2026/03/08 20:03:34
|
|
|
+ * @since 1.0.0
|
|
|
+ */
|
|
|
+ private void dfs(int index,int current, Deque<Integer> deque,int[] candidates,int target,List<List<Integer>> result) {
|
|
|
+ if (current == target) {
|
|
|
+ //记录符合要求的记录
|
|
|
+ List<Integer> list = List.copyOf(deque);
|
|
|
+ result.add(list);
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ if (current > target || index >= candidates.length) {
|
|
|
+ //递归结束
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ //选,选当前这个(下次还可以选)
|
|
|
+ deque.addLast(candidates[index]);
|
|
|
+ dfs(index,current+candidates[index],deque,candidates,target,result);
|
|
|
+ //还原现场
|
|
|
+ deque.removeLast();
|
|
|
+ //不选,选下一个
|
|
|
+ dfs(index+1,current,deque,candidates,target,result);
|
|
|
+ }
|
|
|
+}
|