leetcode 39-Combination Sum(medium)
Posted yshi12
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 39-Combination Sum(medium)相关的知识,希望对你有一定的参考价值。
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.
backtracking
first sort the array, make it low to high
cases:
use a function:(a list to store all combinations, a tinylist store the trial at the moment, a int i store start place of numbers in candidates that we can add to the tinylist(the biggest index of number in tinylist) (avoid duplicates(permutaion))
1. target<0, return;
2. target=0, add tinylist to list and return;
3. start from i, iterate through i->end, everytime add one number to the tinylist, and continue backtracking, remember to remove the added one after backtracking
class Solution { public List<List<Integer>> combinationSum(int[] candidates, int target) { List<List<Integer>> list=new ArrayList<>(); if(target==0||candidates.length==0) return list; Arrays.sort(candidates); findSum(candidates, list, new ArrayList<Integer>(), target, 0); return list; } public void findSum(int[] candidates, List<List<Integer>> list, List<Integer> tinyList, int target, int index){ if(target<0) return; else if(target==0){ list.add(new ArrayList<>(tinyList)); return; } for(int i=index;i<candidates.length;i++){ tinyList.add(candidates[i]); findSum(candidates, list, tinyList, target-candidates[i], i); tinyList.remove(tinyList.size()-1); } } }
以上是关于leetcode 39-Combination Sum(medium)的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode题意分析&解答39. Combination Sum