博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
39. Combination Sum
阅读量:5825 次
发布时间:2019-06-18

本文共 1541 字,大约阅读时间需要 5 分钟。

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

The same repeated number may be chosen from candidates unlimited number of times.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:

Input: candidates = [2,3,6,7], target = 7,A solution set is:[  [7],  [2,2,3]]

Example 2:

Input: candidates = [2,3,5], target = 8,A solution set is:[  [2,2,2,2],  [2,3,3],  [3,5]]

难度:medium

题目:给定一无重复元素的集合和一指定数,找出所有由数组内元素之和为该数的序列。每个元素都可以被无限次使用。

注意:所以元素都为正整数包括给定的整数。答案不允许有重复的组合。

思路:递归

Runtime: 9 ms, faster than 81.90% of Java online submissions for Combination Sum.

Memory Usage: 29.6 MB, less than 16.71% of Java online submissions for Combination Sum.

class Solution {    public List
> combinationSum(int[] candidates, int target) { Arrays.sort(candidates); List
> result = new ArrayList(); combinationSum(candidates, 0, target, 0, new Stack
(), result); return result; } public void combinationSum(int[] cs, int idx, int target, int sum, Stack
stack, List
> result) { if (sum == target) { result.add(new ArrayList(stack)); return; } for (int i = idx; i < cs.length; i++) { if (sum + cs[i] <= target) { stack.push(cs[i]); combinationSum(cs, i, target, sum + cs[i], stack, result); stack.pop(); } if (sum + cs[i] >= target) break; } }}

转载地址:http://pxsdx.baihongyu.com/

你可能感兴趣的文章
构建Docker Compose服务堆栈
查看>>
最小角回归 LARS算法包的用法以及模型参数的选择(R语言 )
查看>>
Hadoop生态圈-Kafka常用命令总结
查看>>
如何基于Redis Replication设计并实现Redis-replicator?
查看>>
浮点数内存如何存储的
查看>>
贪吃蛇
查看>>
EventSystem
查看>>
用WINSOCK API实现同步非阻塞方式的网络通讯
查看>>
玩一玩博客,嘿嘿
查看>>
P1352 没有上司的舞会
查看>>
ios11文件夹
查看>>
【HLOJ 559】好朋友的题
查看>>
Electric Fence(皮克定理)
查看>>
nvl 在mysql中如何处理
查看>>
MyEclipse 快捷键
查看>>
快速傅里叶变换FFT
查看>>
大数据常用基本算法
查看>>
JavaScript学习笔记(十三)——生成器(generator)
查看>>
hibernate保存失败
查看>>
MySQL增量订阅&消费组件Canal POC
查看>>