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

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

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]

思路: 把target number 传入, 每次加入一个数字,就把target number 减去这个数字递归。 当target number == 0 时,说明此时list中的数字的和为target number。 就可以将这组数字加入list里面。 注意可以重复加数字, 所以每次递归传的index就是i。

public class Solution {    public List
> combinationSum(int[] candidates, int target) { List
> result = new ArrayList
>(); List
list = new ArrayList
(); Arrays.sort(candidates); int sum = target; helper(result,list, sum,candidates,0); return result; } private void helper(List
> result, List
list,int sum, int[] candidates,int index) { if (sum == 0) { result.add(new ArrayList
(list)); return; } for (int i = index; i < candidates.length; i++) { if (sum < 0) { break; } list.add(candidates[i]); helper(result,list, sum - candidates[i], candidates,i); list.remove(list.size() - 1); } }}

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

你可能感兴趣的文章
运行于显卡(GPU)的Rootkit木马和键盘记录器问世
查看>>
三星推出高容量、企业级绿色SSD
查看>>
PHP/如何在Linux服务器中隐藏PHP版本
查看>>
高速加密:IBM发布更猛更快的z14大型机
查看>>
任何口令都可访问Advantech工业网关
查看>>
如何让CIO的ITIL实施“一帆风顺”
查看>>
迅雷移动端业务发展迅猛 Q2广告收入同比上涨41.6%
查看>>
迎接数字化社会,华为积极布局
查看>>
阿里云成为CNCF金牌会员 提供云端Kubernetes解决方案
查看>>
F5:亡羊补牢为时已晚,投资网络安全比处理漏洞更划算
查看>>
青云QingCloud推出HBase集群服务 支持SQL等高级功能
查看>>
Windows远程桌面漏洞Esteemaudit(CVE-2017-9073)补丁简要分析
查看>>
Arbor Networks凭借业界全面的 DDoS 防御组合为各类客户提供可用性保护
查看>>
达沃时代帮助VSAN提供NAS方案
查看>>
买服务器网络设备时该考虑哪些因素?
查看>>
悲催的CISO:数据泄露事故的替罪羊
查看>>
2015年十大安全故事回顾
查看>>
数据挖掘与预测分析术语总结
查看>>
寻找“高级威胁”防御的答案
查看>>
“有本事就来抓我呀!”企业发现APT攻击平均需要205天
查看>>