Combination Sum

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

The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.

For example, given candidate set 2,3,6,7 and target 7
A solution set is: 
[7] 
[2, 2, 3]

思路:需要回溯的思想。对数组里面的每个数,用递归的方式叠加,每次递归将和sum与target作比较,若相等则加入结果list,sum>target则舍弃,并返回false,若sum<target,则继续进行递归。第一种sum=target的情况下,在加入结果list后,要将当前一种结果最后加入的元素remove,并继续对后面的元素进行递归;在第二种sum>target的情况下,则需要将当前结果的最后加入的两个元素remove,并继续对后面的元素进行递归。第三种情况sum<target,无需删除直接递归。

注意元素可以重复,所以下一次递归是从当前递归元素开始。

public class S039 {
//backtracking--回溯算法
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<Integer> temp = new ArrayList<Integer>();
Arrays.sort(candidates);//很关键的一步
findConbination(result,temp,0,0,target,candidates);
return result;
}
public boolean findConbination(List<List<Integer>> result,List<Integer> temp,int sum,int level,int target,int[] candidates){
if(sum == target){
result.add(new ArrayList<>(temp)); //从内存复制,防止后面的改变对其发生影响
return true;
}else if(sum>target){
return false;
}else{
for(int i = level;i<candidates.length;i++){//思考level参数的作用
temp.add(candidates[i]);
// sum += candidates[i];思考这一行注释掉并把sum的增加加在下一行参数里面的原因
if(!findConbination(result,temp,sum+candidates[i],i,target,candidates)){//i表示下一次递归从当前递归的位置开始
i = candidates.length;
}
temp.remove(temp.size()-1);
}
return true;
}
}
}

Combination Sum II

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

Each number in C may only be used once in the combination.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.

For example, given candidate set 10,1,2,7,6,1,5 and target 8
A solution set is: 
[1, 7] 
[1, 2, 5] 
[2, 6] 
[1, 1, 6]

思路:与前一题的不同之处在于结果要求同一位置的元素只能出现一次,但是值相同在数组中位置不同的元素可以同时出现。与前一题的不同就是下一次递归都是从当前递归的下一个元素开始。另外测试集不相同,前一题的测试集中不会出现同一数组中有相同的元素,所以不用额外去重。这一题同一数组会出现相同元素,所以得在元素向前移的时候跳过相同的元素来进行去重。

public class S040 {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> rets = new ArrayList<List<Integer>>();
List<Integer> ret = new ArrayList<Integer>();
find(candidates,0,0,target,rets,ret);
return rets;
}
public static boolean find(int[] candidates,int sum,int level,int target,List<List<Integer>> rets,List<Integer> ret){
if(sum == target){
rets.add(new ArrayList<>(ret));
return true;
}else if(sum > target){
return false;
}else{
for(int i = level;i<candidates.length;i++){
ret.add(candidates[i]);
if(!find(candidates,sum+candidates[i],i+1,target,rets,ret)){//i+1表明下一次递归从当前递归的下一位元素开始
i = candidates.length;
}
//去重
while(i<candidates.length-1&&ret.get(ret.size()-1) == candidates[i+1]){
i++;
}
ret.remove(ret.size()-1);
}
return true;
}
}
}

Combination Sum III

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

Ensure that numbers within the set are sorted in ascending order.

Example 1:

Input: k = 3, n = 7

Output:

[[1,2,4]]

Example 2:

Input: k = 3, n = 9

Output:

[[1,2,6], [1,3,5], [2,3,4]]

思路:这一题还是参照了前两题,相当于把前两题中的candidates数组变为nums={1,2,3,4,5,6,7,8,9},然后再在每一次比较结果时加上结果list大小的比较,当前list的大小不超过k。
也不用额外去重。
public class S216 {
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<Integer> temp = new ArrayList<Integer>();
if(n<k*(k+1)/2||n>45||k>9||k<1){
return result;
}
int[] nums = {1,2,3,4,5,6,7,8,9};
find(nums,k,n,0,0,result,temp);
return result;
}
public static boolean find(int[] nums,int k, int n, int sum,int level,
List<List<Integer>> result,List<Integer> temp){
if(temp.size()>k||sum>n){
return false;
}else if(sum == n&&temp.size() == k){
result.add(new ArrayList<>(temp));
return true;
}else{
for(int i = level;i<nums.length;i++){
temp.add(nums[i]);
if(!find(nums,k,n,sum+nums[i],i+1,result,temp)){
i = nums.length;
}
temp.remove(temp.size()-1);
}
return true;
}
}
}
 

Leetcode 39 40 216 Combination Sum I II III的更多相关文章

  1. LeetCode(40) Combination Sum II

    题目 Given a collection of candidate numbers (C) and a target number (T), find all unique combinations ...

  2. LeetCode: Combination Sum I && II && III

    Title: https://leetcode.com/problems/combination-sum/ Given a set of candidate numbers (C) and a tar ...

  3. combination sum(I, II, III, IV)

    II 简单dfs vector<vector<int>> combinationSum2(vector<int>& candidates, int targ ...

  4. leetcode 39. Combination Sum 、40. Combination Sum II 、216. Combination Sum III

    39. Combination Sum 依旧与subsets问题相似,每次选择这个数是否参加到求和中 因为是可以重复的,所以每次递归还是在i上,如果不能重复,就可以变成i+1 class Soluti ...

  5. [LeetCode] 216. Combination Sum III 组合之和 III

    Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...

  6. 39. Combination Sum + 40. Combination Sum II + 216. Combination Sum III + 377. Combination Sum IV

    ▶ 给定一个数组 和一个目标值.从该数组中选出若干项(项数不定),使他们的和等于目标值. ▶ 36. 数组元素无重复 ● 代码,初版,19 ms .从底向上的动态规划,但是转移方程比较智障(将待求数分 ...

  7. Java for LeetCode 216 Combination Sum III

    Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...

  8. Leetcode 216. Combination Sum III

    Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...

  9. LeetCode:Combination Sum I II

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

随机推荐

  1. Hex Workshop(16进制编辑利器) 6.7.2绿色版

    软件名称: Hex Workshop 6.7.2绿色版(16进制编辑利器) 软件语言: 简体中文 授权方式: 免费软件 运行环境: Win 32位/64位 软件大小: 1.8MB 图片预览: 软件简介 ...

  2. Python 实现类似PHP的strip_tags函数功能,并且可以自定义设置保留标签

    最近在研究 Python ,发现用的还是很不习惯,很多PHP里面很简单的功能在Python 里面都得找半天,而且很多功能都得自己实现. 今天做个采集,需要过滤内容中的标签,搞了一下午,貌似终于搞出来了 ...

  3. Mac OS启动服务优化高级篇(launchd tuning)

    Mac下的启动服务主要有三个地方可配置:1,系统偏好设置->帐户->登陆项2,/System/Library/StartupItems 和 /Library/StartupItems/3, ...

  4. scale-free network

    原文链接:http://lihailian.bokee.com/6013647.html 1.什么是无尺度现象? 统计物理学家习惯于把服从幂次分布的现象称为无尺度现象. 在做大量统计实验之前,科学家预 ...

  5. 第八章 监控 Zabbix

    1.1   YUM部署 Zabbix 2.4 1.  前期准备(省略) l   Yum源的配置 cd /etc/yum.repos.d/; mkdir old;mv ./* old/ rpm -Uvh ...

  6. C# 语言规范_版本5.0 (第7章 表达式)

    1. 表达式 表达式是一个运算符和操作数的序列.本章定义语法.操作数和运算符的计算顺序以及表达式的含义. 1.1 表达式的分类 一个表达式可归类为下列类别之一: 值.每个值都有关联的类型. 变量.每个 ...

  7. Gulp安装使用教程

    题记:为什么要使用gulp,网上有很多关于gulp的优势,而在我看来,这些都是工具的优势!工具的优势最主要体现在易用性上,听说gulp比grunt更易用,所以这里写个文档记录. 同样要保证nodejs ...

  8. 在IT界取得成功应该知道的10件事

    导读:人人似乎都同意IT行业是一个艰难领域,但怎样才能克服逆境,成为一名成功的IT专业人士呢?下文这些特质应该是关键.此文作者Jack Wallen,他在前段时间写过不少文章讨论IT职场,比如退出IT ...

  9. Leetcode - 186 Reverse Words in a String II

    题目: Given an input string, reverse the string word by word. A word is defined as a sequence of non-s ...

  10. css中position中的几个属性

    static  是默认值.任意 position: static; 的元素不会被特殊的定位.一个 static 元素表示它不会被"positioned",一个 position 属 ...