1. 原题链接
https://leetcode.com/problems/combination-sum/description/
2. 题目要求
给定一个整型数组candidates[ ]和目标值target,找出数组中累加之后等于target的所有元素组合
注意:(1)数组中的每一个元素可以重复用;(2)数组中不存在重复元素;(3)数组中都是正整数
3. 解题思路
采用迭代的方法检验所有元素组合
4. 代码实现
1 import java.util.ArrayList; 2 import java.util.List; 3 4 public class CombinationSum39 { 5 public static void main(String[] args) { 6 CombinationSum39 cs = new CombinationSum39(); 7 int[] candidates = {2,3,6,7}; 8 for (List l1:cs.combinationSum(candidates,7)){ 9 System.out.println(l1.toString()); 10 System.out.println(); 11 } 12 13 } 14 public List<List<Integer>> combinationSum(int[] candidates, int target) { 15 List<List<Integer>> result = new ArrayList<List<Integer>>(); 16 combinationSum(result,new ArrayList<Integer>(),candidates,target,0); 17 return result; 18 } 19 public void combinationSum(List<List<Integer>> result, List<Integer> cur, int[] candidates, int target,int start) { 20 if (target > 0) { 21 for (int i = start;i < candidates.length;i++) { 22 cur.add(candidates[i]); 23 combinationSum(result, cur, candidates, target-candidates[i],i); 24 cur.remove(cur.size() - 1); 25 } 26 } 27 if (target == 0) 28 result.add(new ArrayList<Integer>(cur)); 29 } 30 }
原文地址:https://www.cnblogs.com/huiAlex/p/8227434.html
时间: 2024-10-08 19:25:15