[LeetCode] 40. Combination Sum II Java
Posted BrookLearnData
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 40. Combination Sum II Java相关的知识,希望对你有一定的参考价值。
题目:
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的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode OJ 40. Combination Sum II
[array] leetcode - 40. Combination Sum II - Medium