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
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
67 lines (53 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 set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. | |
The same repeated number may be chosen from candidates unlimited number of times. | |
Note: | |
All numbers (including target) will be positive integers. | |
The solution set must not contain duplicate combinations. | |
Example 1: | |
Input: candidates = [2,3,6,7], target = 7, | |
A solution set is: | |
[ | |
[7], | |
[2,2,3] | |
] | |
Example 2: | |
Input: candidates = [2,3,5], target = 8, | |
A solution set is: | |
[ | |
[2,2,2,2], | |
[2,3,3], | |
[3,5] | |
] | |
My code: | |
import numpy as np | |
class Solution: | |
def combinationSum(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 | |
lists=self.combinationSum(candidates,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/ |