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]

题目大意:给一个候选数组,一个目标值,从候选数组找出所有和等于目标值的List,候选数组元素可以重复。

解题思路:还是用回溯的方式来做,因为可以重复,所以每次都可以从当前元素开始往后依次添加到List,递归判断,然后回溯。

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
if (candidates == null || candidates.length == 0) {
return res;
}
List<Integer> tmp = new ArrayList<>();
helper(res, tmp, 0,candidates, target);
return res;
} private void helper(List<List<Integer>> res, List<Integer> tmp, int start,int[] candidates, int target) {
if (0 == target) {
res.add(new ArrayList<>(tmp));
// System.out.println(tmp);
return;
}
for (int i = start; i < candidates.length && target >= candidates[i]; i++) {
tmp.add(candidates[i]);
helper(res, tmp, i,candidates, target - candidates[i]);
tmp.remove(tmp.size() - 1);
int ca = candidates[i];
while(i<candidates.length&&ca==candidates[i]){
i++;
}
}
}

最新文章

  1. tornado学习笔记19 Tornado框架分析
  2. sql2000新建登陆用户错误“21002:[SQL-DMO] 用户***已经存在”的原因和解决方法【孤立用户解决方法】
  3. zabbix 安装
  4. iOS,Xcod7/8,iOS使用修改点
  5. 【转】关于KDD Cup '99 数据集的警告,希望从事相关工作的伙伴注意
  6. ZOJ 1068 P,MTHBGWB
  7. Sublime Text 2入门指南
  8. 从零开始学习前端开发 — 9、标签嵌套规则及CSS常用样式覆盖
  9. Properties读取properties配置文件
  10. 饮冰三年-人工智能-linux-04 vim编辑器
  11. Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.0:compile (default-compile) on project demo: Fatal error com piling: 无效的标记: -parameters
  12. 关于java和jvm的思考
  13. BZOJ2199[Usaco2011 Jan]奶牛议会——2-SAT+tarjan缩点
  14. TCP可靠传输:校验和,重传控制,序号标识,滑动窗口、确认应答
  15. 【代码笔记】iOS-计算时间差
  16. Controller中添加一个异步的Action
  17. Alpha 冲刺九
  18. github上不去了
  19. expect 分发ssh key脚本
  20. 温故而知新 gulp.src 指定数组文件夹

热门文章

  1. 使用ListView 时,遇到了 Your content must have a ListView whose id attribute is &#39;android.R.id.list&#39; 错误
  2. Sqlserver通过链接服务器访问Oracle
  3. c# 为什么要用 get set 属性
  4. oracle中不曾熟悉的 to_char、to_number(未完待续)
  5. Xcode的控制台调试命令
  6. JavaScript_变量的自动转换和语句
  7. Windows程序设计 贪吃蛇c
  8. 【POJ3580】【splay版】SuperMemo
  9. 工厂方法模式(Factory Method)
  10. 下拉框&mdash;&mdash;把一个select框中选中内容移到另一个select框中遇到的问题