LeetCode_OJ【39】Combination Sum
来源:互联网 发布:苹果版软件商店 编辑:程序博客网 时间:2024/06/03 12:36
Given a set of candidate numbers (C) and a target number (T), find all unique combinations inC 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.
2,3,6,7
and target 7
, A solution set is:
[7]
[2, 2, 3]
给定数组和目标值,从数组中找到所有的组合,使得组合的总和等于目标值,数组中的值可以重复选取。
这个题目的主要思路就是递归回溯,说来惭愧,好久没写递归,答案还是参考了别人的。
下面是本题的java实现。
public class Solution {public List<List<Integer>> combinationSum(int[] candidates, int target) {List<List<Integer>> res = new ArrayList<List<Integer>>();List<Integer> tmp = new ArrayList<Integer>();dfs(res,tmp,candidates,target,0);return res; }public void dfs(List<List<Integer>> res,List<Integer> tmp,int[] candidates, int gap,int index){if(gap == 0){List<Integer> list = new ArrayList<Integer>(tmp); res.add(list);return;}for(int i = index ; i < candidates.length; i++){if(gap < candidates[index])return;else{tmp.add(candidates[i]);gap -= candidates[i];dfs(res,tmp,candidates,gap,i);tmp.remove(tmp.size()-1);}}}}
0 0
- LeetCode_OJ【39】Combination Sum
- LeetCode_OJ【40】Combination Sum II
- LeetCode_OJ【15】3Sum
- LeetCode_OJ【18】4Sum
- LeetCode 39: Combination Sum
- LeetCode(39) Combination Sum
- [leetcode 39] Combination Sum
- leetcode 39: Combination Sum
- leetcode || 39、Combination Sum
- 39-m-Combination Sum
- leetcode 39 : Combination Sum
- leetcode 39: Combination Sum
- Leetcode #39 Combination Sum
- LeetCode(39) Combination Sum
- LeetCode-39 Combination Sum
- 39 Combination Sum
- 39Combination Sum
- leetcode 39:Combination Sum
- libevent7
- html与htm的区别
- 基于Windows Socket的安全通信(C++实现,附源码)
- 浏览器缓存机制
- C#实现MD5加密
- LeetCode_OJ【39】Combination Sum
- 'the django book'读书笔记(第1,2章)
- 通过ssh操作IOS亮屏解锁打开app
- AppleScript学习(重要)
- poj--2631--Roads in the North(树的直径 裸模板)
- python的LEGB原则
- iOS之arc与mrc的混合使用
- wireshark分析H264媒体包
- Opencv3.1+python2.7的CentOS7安装