zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    js正则小记
    github相关
    js设置 获取 删除cookie
    js传递数据一些方式
    js call()方法
    DOM节点相关操作(兼容)
    git 常用命令总结
    js中的this指向
    angular 中 directive中的多个指令
    指令中 controller && controllerAs
  • 原文地址:https://www.cnblogs.com/kexinxin/p/10163015.html
Copyright © 2011-2022 走看看