[LeetCode] 40. Combination Sum II Java
阿新 • • 發佈:2017-06-05
array lec span mov ont integer target else list
題目:
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
- All numbers (including target) will be positive integers.
- The solution set must not contain duplicate combinations.
For example, given candidate set [10, 1, 2, 7, 6, 1, 5]
and target 8
,
A solution set is:
[ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]
題意及分析:這道題比上一題多了一個約束條件,即元素不能重復使用,所以只需要在下一次回溯時將起始點的位置加一即可。具體見代碼。
代碼:
public class Solution { public List<List<Integer>> combinationSum2(int[] candidates, int target) { Arrays.sort(candidates); List<Integer> array= new ArrayList<>(); List<List<Integer>> list = new ArrayList<>(); int start=0; int remain=target; backTracking(list,array,candidates,start,remain); return list; } public void backTracking(List<List<Integer>> list,List<Integer> array,int[] candidates,int start,int remain) { if(remain<0) return; else if(0==remain){ //有解 list.add(new ArrayList<>(array)); }else{ for(int i=start;i<candidates.length;i++){ if(i>start&&candidates[i]==candidates[i-1]) continue; //去重 array.add(candidates[i]); backTracking(list, array, candidates, i+1, remain-candidates[i]); //這裏是i+1 array.remove(array.size()-1); } } return; } }
[LeetCode] 40. Combination Sum II Java