Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
LeetCode/Combination Sum II
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
63 lines (55 sloc)
1.67 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. | |
Each number in candidates 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. | |
Example 1: | |
Input: candidates = [10,1,2,7,6,1,5], target = 8, | |
A solution set is: | |
[ | |
[1, 7], | |
[1, 2, 5], | |
[2, 6], | |
[1, 1, 6] | |
] | |
Example 2: | |
Input: candidates = [2,5,2,1,2], target = 5, | |
A solution set is: | |
[ | |
[1,2,2], | |
[5] | |
] | |
My code: | |
class Solution: | |
def combinationSum2(self, candidates, target): | |
""" | |
:type candidates: List[int] | |
:type target: int | |
:rtype: List[List[int]] | |
""" | |
if target<0: | |
return [] | |
final_list=[] | |
for item in candidates: | |
if item==target: | |
tmp_list=[item] | |
final_list.append(tmp_list) | |
if item>target: | |
continue | |
tmp_candidate=candidates.copy() | |
tmp_candidate.remove(item) | |
lists=self.combinationSum2(tmp_candidate,target-item) | |
if len(lists)>0: | |
for tmp_list in lists: | |
#print(tmp_list) | |
tmp_list.append(item) | |
tmp_list.sort() | |
#if tmp_list not in final_list: | |
final_list.append(tmp_list) | |
final_list1=[] | |
for item in final_list: | |
if item not in final_list1: | |
final_list1.append(item) | |
return final_list1 | |
Solution: | |
https://leetcode.com/problems/combination-sum-ii/ |