java
class Solution {
List<List<Integer>> res=new ArrayList<>();
List<Integer> li=new ArrayList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
solut(candidates,target,0,0);
return res;
}
void solut(int[] candidates, int target,int index,int listSum){
if(listSum==target){
res.add(new ArrayList<>(li));
return;
}
for(int i=index;i<candidates.length&&listSum<=target;i++){
if(i>index&&candidates[i]==candidates[i-1]){
continue;
}
li.add(candidates[i]);
listSum+=candidates[i];
solut(candidates,target,i+1,listSum);
listSum-=li.get(li.size()-1);
li.remove(li.size()-1);
}
}
}
python
class Solution(object):
def combinationSum2(self, candidates, target):
res=[]
li=[]
def solut(candidates,target,index,listSum):
if listSum>target:
return
if listSum==target:
res.append(li[:])
return
for i in range(index,len(candidates)):
if i>index and candidates[i]==candidates[i-1]:
continue
li.append(candidates[i])
listSum+=candidates[i]
solut(candidates,target,i+1,listSum)
listSum-=li.pop()
candidates=sorted(candidates)
solut(candidates,target,0,0)
return res