https://leetcode.com/problems/combination-sum-ii/#/description
问题描述:
给定一个数组(有重复元素),和一个目标值,找出这个数组的子集,是这个自己的元素和为这个目标值。 数组中的元素只能使用一次。
思路解析:
参考http://blog.csdn.net/u013275928/article/details/72588102
稍加改动就可以,由于一个元素只可以使用一次,但是数组中可以有重复元素,所以参数中的pos应置i+1,从它的下一位开始,然后判断result中是否已经存在了templist,是用ArrayList的contains方法就可以判断。
代码如下:
public class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> result=new ArrayList<>();
getSub(result,new ArrayList<>(),candidates,0,target);
return result;
}
public void getSub(List<List<Integer>> result,List<Integer> temp,int[] nums,int pos,int target)
{
if(target<0)return;
if(target==0&& !result.contains(temp))
{
result.add(new ArrayList<>(temp));
}
for(int i=pos;i<nums.length;i++)
{
temp.add(nums[i]);
getSub(result,temp,nums,i+1,target-nums[i]);
temp.remove(temp.size()-1);
}
}
}