leetcode - 39. Combination Sum - Medium

descrition

Given a set of candidate numbers (C) (without duplicates) 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.
  • 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]
]

解析

典型的回溯法求解。代码实现中给出了 3 中回溯的方式,都 accepted。微妙的区别应该是在递归的层数不同。对于 candidates[index] 只有两种情况,即:选择或不选择,值得注意的是如果选择的话可以多次重复选择。(可以使用状态转换图进行抽象更便于理解,重复选择实际上是在 index 状态有环,而不选择则是向 index + 1 状态的迁移)

注意:

  • 调用函数前用了一个排序,主要是为了递归时剪枝做准备,数组是递增排序,如果太大则可以停止更深层的递归
  • 题目说了所有数都是 positive,这其实也可以作为剪枝的条件
  • 题目说数组中不存在 duplicate 元素,如果存在的话还需要跳过重复的元素。

一般的,对于回溯问题,找好递归求解的子结构,记得结束点即出口的检查,避免无限循环。在递归过程中可以思考是否可以进行剪枝。

code


#include <iostream>
#include <vector>
#include <algorithm> using namespace std; class Solution{
public:
vector<vector<int> > combinationSum(vector<int>& candidates, int target){
vector<vector<int> > ans;
vector<int> vecCur;
sort(candidates.begin(), candidates.end()); combinationSumBacktracking0(candidates, 0, target, vecCur, ans);
//combinationSumBacktracking1(candidates, 0, target, vecCur, ans);
//combinationSumBacktracking2(candidates, 0, target, vecCur, ans);
return ans;
} // candidates in ascending
void combinationSumBacktracking0(vector<int>& candidates, int index, int target,
vector<int>& vecCur, vector<vector<int> >& ans){
if(target < 0)
return;
if(target == 0 && !vecCur.empty()){
ans.push_back(vecCur);
return;
}
// sub-problem, for each element in candidates[index,...,n-1]
// just have two condition: choose or not
for(int i=index; i<candidates.size(); i++){
if(candidates[i] > target) // Note: candidates must in ascending order
break;
// note: not i+1, because the same repeaded number may be chosen from candidates
vecCur.push_back(candidates[i]);
combinationSumBacktracking0(candidates, i, target - candidates[i], vecCur, ans);
vecCur.pop_back();
}
} void combinationSumBacktracking1(vector<int>& candidates, int index, int target,
vector<int>& vecCur, vector<vector<int> >& ans){
if(target < 0)
return;
if(target == 0){
if(!vecCur.empty())
ans.push_back(vecCur);
return;
}
if(index >= candidates.size())
return; // choose candidates[index]
// Note: candidates[index] can be choose more than onece
vecCur.push_back(candidates[index]);
combinationSumBacktracking1(candidates, index, target - candidates[index], vecCur, ans);
vecCur.pop_back(); // dosen't choose candidates[index]
combinationSumBacktracking1(candidates, index+1, target, vecCur, ans);
} void combinationSumBacktracking2(vector<int>& candidates, int index, int target,
vector<int>& vecCur, vector<vector<int> >& ans){
if(target < 0)
return;
if(target == 0){
if(!vecCur.empty())
ans.push_back(vecCur);
return;
}
if(index >= candidates.size())
return; // choose candidates[index] more than times
int i = 1;
for(; i*candidates[index] <= target; i++){
vecCur.push_back(candidates[index]);
combinationSumBacktracking2(candidates, index+1, target - i*candidates[index], vecCur, ans);
}
for(int j=i-1; j>=1; j--)
vecCur.pop_back(); // don't choose candidates[index]
combinationSumBacktracking2(candidates, index+1, target, vecCur, ans);
}
}; int main()
{
return 0;
}

[array] leetcode - 39. Combination Sum - Medium的更多相关文章

  1. [array] leetcode - 40. Combination Sum II - Medium

    leetcode - 40. Combination Sum II - Medium descrition Given a collection of candidate numbers (C) an ...

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

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

  3. [LeetCode] 39. Combination Sum 组合之和

    Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), fin ...

  4. LeetCode 39. Combination Sum (组合的和)

    Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique c ...

  5. Java [Leetcode 39]Combination Sum

    题目描述: Given a set of candidate numbers (C) and a target number (T), find all unique combinations in  ...

  6. LeetCode 39 Combination Sum(满足求和等于target的所有组合)

    题目链接: https://leetcode.com/problems/combination-sum/?tab=Description   Problem: 给定数组并且给定一个target,求出所 ...

  7. [LeetCode] 39. Combination Sum ☆☆☆(数组相加等于指定的数)

    https://leetcode.wang/leetCode-39-Combination-Sum.html 描述 Given a set of candidate numbers (candidat ...

  8. Leetcode 39. Combination Sum

    Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique c ...

  9. leetcode 39 Combination Sum --- java

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

随机推荐

  1. Python [习题] 字典排序

    [习题] 对此字典分别按照value 和key 如何排序? dic1 = {'and':40, 'a':54, 'is':60, 'path':139, 'the':124, 'os':49} In ...

  2. SSE图像算法优化系列十二:多尺度的图像细节提升。

    无意中浏览一篇文章,中间提到了基于多尺度的图像的细节提升算法,尝试了一下,还是有一定的效果的,结合最近一直研究的SSE优化,把算法的步骤和优化过程分享给大家. 论文的全名是DARK IMAGE ENH ...

  3. centos6.7安装openblas错误

    centos系统:CentOS release 6.7 (Final)安装OpenBLAS # Install OpenBLAS at /usr/local/openblas git clone ht ...

  4. python利用for..in遍历,while循环嵌套编译九九乘法表的几种模式

    运用for....in...遍历的四种方向的九九乘法表: 左下角: import sysfor i in range(1,10): for j in range(1,i+1): sys.stdout. ...

  5. [smartMenu.js] 一个基于jquery的实用的右键拓展菜单栏插件

    正在为电子书阅读器添加精准易用的标记功能,其中一个方案是扩展阅读器界面的右键菜单栏,使得用户右键点击某个词.子句.段落的时候可以进行扩展操作. 右键菜单栏有很多基于jQuery的插件,其中灵活性比较强 ...

  6. js 获取每月有几周,根据年月周获取该周从周一到周日的日期等方法

    本文基于react-native 本人在用react-native写一个关于课程表的APP时需要课程表按照日期周期显示,网上查了许多方法,都没有达到自己想要的效果,根据一些方法的参考,再根据自己思维写 ...

  7. 【MySQL疑难杂症】如何将树形结构存储在数据库中(方案一、Adjacency List)

    今天来看看一个比较头疼的问题,如何在数据库中存储树形结构呢? 像mysql这样的关系型数据库,比较适合存储一些类似表格的扁平化数据,但是遇到像树形结构这样有深度的人,就很难驾驭了. 举个栗子:现在有一 ...

  8. springmvc关于前台日期作为实体类对象参数类型转换错误

    页面报错: 后台错误: Field error in object 'user' on field 'birthday': rejected value [2013-06-24]; codes [ty ...

  9. spring boot与jdbcTemplate的整合案例2

    简单入门了spring boot后,接下来写写跟数据库打交道的案例.博文采用spring的jdbcTemplate工具类与数据库打交道. 下面是搭建的springbootJDBC的项目的总体架构图: ...

  10. 是否是有效的dom节点--轮子代码

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title> ...