Leetcode 39.组合总数

组合总数

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的数字可以无限制重复被选取。

说明:

  • 所有数字(包括 target)都是正整数。
  • 解集不能包含重复的组合。 

示例 1:

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

所求解集为:

[

[7],

[2,2,3]

]

 

 

解题思路:

我个人感觉该题目一点也不难,其实也是一个递归的过程,当达到递归条件时,就将结果加入结果集;

首先题目没说给的数组有啥特性,因此我先将数组进行了排序,这样在某个点找不着结果,那后面的都比target大,自然也就没有结果了。废话不多说,直接看代码;

代码如下:

 

 1 import java.util.*;
 2 public class Solution {
 3     public List<List<Integer>> combinationSum(int[] candidates, int target) {
 4         List<List<Integer>> LList = new ArrayList<List<Integer>>();  // 最终的结果集
 5         if(candidates == null || candidates.length < 1 || target < 1 )
 6             return LList;
 7         Arrays.sort(candidates);  // 排序,使得不用对相同的结果集计算多次
 8         List<Integer> list = new ArrayList<Integer>();  // 临时结果保存
 9         combinationSumCore(candidates,list, target, 0, LList);  // 核心函数
10         return LList;
11     }
12     public void combinationSumCore(int[] candidates,List<Integer> list, int target, int index, List<List<Integer>> LList)
13     {
14         for(int i = index; i < candidates.length; i++)
15         {
16             if(candidates[i] == target)  // 等于,就加入结果集
17             {
18                 List<Integer> result = new ArrayList<Integer>();
19                 result.addAll(list);
20                 result.add(candidates[i]);
21                 LList.add(result);
22             }
23             else if(candidates[i] < target)  // 小于,就继续递归
24             {
25                 List<Integer> result = new ArrayList<Integer>();
26                 result.addAll(list);
27                 result.add(candidates[i]);
28                 combinationSumCore(candidates, result, target - candidates[i], i, LList);  // 这边i值不变,是因为当前值可以使用多次
29             }
30             else  // 大于,则后面的数字都大于,因此不可能出现在结果集中
31             {
32                 break;
33             }
34         }
35     }
36 }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值