题目描述:
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.
- Elements in a combination (a 1, a 2, … , a k) must be in non-descending order. (ie, a 1 ≤ a 2 ≤ … ≤ a k).
- The solution set must not contain duplicate combinations.
For example, given candidate set10,1,2,7,6,1,5and target8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
思路解析:
- 从目标的数组中组成target数值,注意此时不要使用num的重复的数字元素。所以不要忘记排序哦!
- 与前一个的区别是,不能使用一个元素多次,所以要建立一个boolean的数组,用于记录每一个是不是都已经被访问了
- 注意判断是不是重复组合的时候,判断的是visited[i-1]是不是false,如果是false 的话,就说明前一个没有访问,那么直接访问第i个的话,就重复了
代码:
import java.util.*;
public class Solution {
public ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
if(num == null||num.length==0)
return res;
ArrayList<Integer> item = new ArrayList<Integer>();
Arrays.sort(num);
boolean[] visited = new boolean[num.length];
helper(num,target,0,item,res,visited);
return res;
}
private void helper(int[] num,int target,int start,ArrayList<Integer> item,ArrayList<ArrayList<Integer>> res,boolean[] visited){
if(target<0)
return;
if(target==0){
res.add(new ArrayList<Integer>(item));
return;
}
for(int i=start;i<num.length;i++){
if(!visited[i]){
if(i>0&&num[i]==num[i-1]&&visited[i-1]==false)
continue;
item.add(num[i]);
visited[i]=true;
int newtarget = target-num[i];
helper(num,newtarget,i+1,item,res,visited);
visited[i]=false;
item.remove(item.size()-1);
}
}
}
}