目录
学习目标
- 39. 组合总和
- 40.组合总和II
- 131.分割回文串
学习内容
39. 组合总和
39. 组合总和 - 力扣(LeetCode)https://leetcode.cn/problems/combination-sum/
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
res = []
def dfs(index,amount,tmp):
if amount==target:
res.append(tmp.copy())
return
for i in range(index,len(candidates)):
if amount+candidates[i]<=target:
dfs(i,amount+candidates[i],tmp+[candidates[i]])
dfs(0,0,[])
return res
40.组合总和II
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
res = []
candidates.sort()
print(candidates)
def dfs(index,amount,tmp):
if amount==target:
res.append(tmp.copy())
return
if index==len(candidates):
return
for i in range(index,len(candidates)):
if i-1 >= index and candidates[i]==candidates[i-1]:
continue
if amount+candidates[i]<=target:
dfs(i+1,amount+candidates[i],tmp+[candidates[i]])
dfs(0,0,[])
return res
131.分割回文串
131. 分割回文串 - 力扣(LeetCode)https://leetcode.cn/problems/palindrome-partitioning/
class Solution:
def partition(self, s: str) -> List[List[str]]:
res = []
n = len(s)
def dfs(i,tmp):
if i==n:
res.append(tmp.copy())
return
for j in range(i,n):
if s[i:j+1]==s[i:j+1][::-1]:
dfs(j+1,tmp+[s[i:j+1]])
dfs(0,[])
return res