LeetCode:39. Combination Sum(Medium)

Posted 一只敲码的猫

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode:39. Combination Sum(Medium)相关的知识,希望对你有一定的参考价值。

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 }

 

以上是关于LeetCode:39. Combination Sum(Medium)的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode题意分析&解答39. Combination Sum

Leetcode 39. Combination Sum

[leetcode-39-Combination Sum]

leetcode 39. Combination Sum

[array] leetcode - 39. Combination Sum - Medium

LeetCode39Combination Sum