题目描述

给定一个无重复的正整数数组 candidates 和一个正整数 target, 求所有和为 target 的 candidates 中数的组合中。其中相同数的不同顺序组合算做同一种组合,candidates 中的数可以重复使用。

算法一

首先想到的方法就是枚举所有的组合可能性,判断其和是否为target。枚举的方法可以使用递归,对candidates中每一个数,有“加入组合”和“不加入组合”两种选择,每一种选择又可以向后面元素的不同选择递归,直到candidate中最后一个元素。可以用剪枝来减少算法的运行时间,如果当前组合的和大于target,则当前情形下已不会有合适的组合了。
AC代码如下:
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
dfs(candidates, 0, target, new ArrayList<Integer>(), res);
return res;
} private void dfs(int[] candidates, int index, int target, List<Integer> combination, List<List<Integer>> res) {
if(target < 0) return;
if(target == 0) {
res.add(new ArrayList<>(combination));
return;
} for(int i=index; i<candidates.length; i++) {
if(candidates[i] > target) continue;
//选择当前元素
combination.add(candidates[i]);
dfs(candidates, i, target - candidates[i], combination, res);
//不选择当前元素
combination.remove(combination.size() - 1);
}
}
}

算法二

本题符合动态规划的思想,用一个map记录不同target的全部组合,target <=  0的组合为空, target = i的组合为全部 target = i - candidates[j] (0<j<candidates.length)的组合加上candidates[j]。
这里需要注意,因为题目要求相同元素的不同顺序算同一种组合方式,上诉方法会出现[2,3,2] 和 [2,2,3]这样两种组合方式。可以用将每一种组合排序后加入set的方法来去重。
AC代码:
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Map<Integer, List<List<Integer>>> dp = new HashMap<Integer, List<List<Integer>>>();
return dp(target, 0, candidates, dp);
} private List<List<Integer>> dp(int target, int index, int[] candidates, Map<Integer, List<List<Integer>>> map){
if(map.containsKey(target)) {
return map.get(target);
} List<List<Integer>> resList = new ArrayList<>();
Set<List<Integer>> resSet = new HashSet<>(); //这里一定要能够区分出 小于0和等于0. 等于0时加一个空的,避免出现[2,3,6,7] ,target = 7时,6被放入其中!!!!
if(target < 0 ) return resList;
if(target == 0){
resList.add(new ArrayList<>());
return resList;
} for(int i=index; i<candidates.length; i++){
List<List<Integer>> subResList = dp(target - candidates[i], index, candidates, map);
if(subResList.size() > 0) {
for(List<Integer> subRes : subResList) {
List<Integer> res = new ArrayList<>(subRes);
res.add(candidates[i]);
Collections.sort(res);
resSet.add(res);
}
}
}
for(List<Integer> l : resSet) {
resList.add(l);
} map.put(target, resList);
return resList;
}
}

算法三

本题还可以采用背包问题的思想,target相当于背包的容量,candidates为物品。
用一个map记录sum的范围从0~target的所有组合,容量为 i 的组合求解方式如下:遍历每一个物品candidates[j], 获取容量为 i - candidates[j]的所有组合,加入该物品。
这里值得注意的是,因为题目要求相同元素的不同顺序算同一种组合方式,因此需要将物品的循环放在容量循环的外面,这样就可以避免出现重复出现[2,3,2] 和 [2,2,3]这样两种组合方式。
AC代码:
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Map<Integer, List<List<Integer>>> m = new HashMap<>();
m.put(0, new ArrayList<List<Integer>>()); for(int i=0; i<candidates.length; i++){
for(int j=0; j<=target; j++){
if(j < candidates[i]) continue;
List<List<Integer>> l = m.get(j - candidates[i]);
if(l != null) {
List<List<Integer>> jList = m.getOrDefault(j, new ArrayList<List<Integer>>());
if(l.size() == 0){
List<Integer> lcurr = new ArrayList<>();
lcurr.add(candidates[i]);
jList.add(lcurr);
}else{
for(List<Integer> listInL : l){
List<Integer> lcurr = new ArrayList<>(listInL);
lcurr.add(candidates[i]);
jList.add(lcurr);
}
}
m.put(j, jList);
}
}
}
return m.getOrDefault(target, new ArrayList<List<Integer>>());
}
}

LeetCode笔记:39. Combination Sum的更多相关文章

  1. [Leetcode][Python]39: Combination Sum

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 39: Combination Sumhttps://oj.leetcode. ...

  2. LeetCode题解39.Combination Sum

    39. Combination Sum Given a set of candidate numbers (C) (without duplicates) and a target number (T ...

  3. 【LeetCode】39. Combination Sum (2 solutions)

    Combination Sum Given a set of candidate numbers (C) and a target number (T), find all unique combin ...

  4. 【一天一道LeetCode】#39. Combination Sum

    一天一道LeetCode系列 (一)题目 Given a set of candidate numbers (C) and a target number (T), find all unique c ...

  5. LeetCode OJ 39. Combination Sum

    Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C wher ...

  6. LeetCode:39. Combination Sum(Medium)

    1. 原题链接 https://leetcode.com/problems/combination-sum/description/ 2. 题目要求 给定一个整型数组candidates[ ]和目标值 ...

  7. 【LeetCode】39. Combination Sum 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:递归 方法二:回溯法 日期 题目地址:[htt ...

  8. 【一天一道LeetCode】#40. Combination Sum II

    一天一道LeetCode系列 (一)题目 Given a collection of candidate numbers (C) and a target number (T), find all u ...

  9. [array] leetcode - 39. Combination Sum - Medium

    leetcode - 39. Combination Sum - Medium descrition Given a set of candidate numbers (C) (without dup ...

  10. 39. Combination Sum - LeetCode

    Question 39. Combination Sum Solution 分析:以candidates = [2,3,5], target=8来分析这个问题的实现,反向思考,用target 8减2, ...

随机推荐

  1. LeetCode第十五题-找出数组中三数和为0的答案

    3Sum 问题简介: 给定n个整数的数组nums,是否有元素a,b,c在nums中,使a + b + c = 0? 找到数组中所有唯一的三元组,它们的总和为零 注:解决方案集不得包含重复的三元组 例如 ...

  2. 吴恩达《机器学习》编程作业——machine-learning-ex1:线性回归

    ❄❄❄❄❄❄❄❄[回到目录]❄❄❄❄❄❄❄❄ 本次编程作业中,需要完成的代码有如下几部分: [⋆] warmUpExercise.m - Simple example function in Octa ...

  3. noip2018游(AFO)记

    Day 0 到学车了,已经差不多四点了,领完一小袋比赛要用的就匆匆回了宾馆. 话说之前看地图的时候我们的宾馆最远,而且名字听起来并没有怎么高大上, 一看隔壁度豪大酒店就感觉应该比我们的酒店好.然鹅到了 ...

  4. ansible-plabybook 常用的有用的命令

    ansible-plabybook 常用的有用的命令 ansible-playbook常用的非常有用的参数有: -C ,大写c ,这个命令的意思就是模拟执行,会告诉你跑完这个playbook会发生什么 ...

  5. 《Linux就该这么学》 - 必读的红帽系统与红帽linux认证自学手册

    <Linux就该这么学>   本书作者刘遄从事于linux运维技术行业,较早时因兴趣的驱使接触到了Linux系统并开始学习. 已在2012年考下红帽工程师RHCE_6,今年又分别考下RHC ...

  6. 启动Eclipse发生错误:An internal error occurred during: "Initializing Java Tooling".

    问题描述   由于上一次关闭 Eclipse 时没有正常关闭,再次启动 Eclipse 时报错:An internal error occurred during: "Initializin ...

  7. GraphQL ---02 GraphQL和C#结合的实战项目

    本文章是介绍和记录如何创建GraphQL项目,以及如何使用GraphQL进行数据的相关操作.项目参照GraphQL .Net 的官方文档进行实践 一.项目结构: 为了更好的和原有的项目结合在一起,尽可 ...

  8. YARN配置

    环境搭建 mapred-site.xml <configuration> <property> <name>mapreduce.framework.name< ...

  9. OpenCV-Python-图像梯度

    图像梯度 我们知道一阶导数可以用来求极值.把图片想象成连续函数,因为边缘部分的像素值与旁边的像素明显有区别,所以对图片局部求极值,就可以得到整幅图片的边缘信息.不过图片是二维的离散函数,导数就变成了差 ...

  10. 从Uber微服务看最佳实践如何炼成?

    导读:Uber成长非常迅速,工程师团队快速扩充,据说Uber有2000名工程师,8000个代码仓库,部署了1000多个微服务.微服务架构是Uber应对技术团队快速增长,功能快速上线很出色的解决方案.本 ...