一、原题目
Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
Note:
- All numbers will be positive integers.
- The solution set must not contain duplicate combinations.
二、题目大意
给定两个整数k和n,对1-9之间的数字进行组合构成一个列表,这个列表满足:元素个数为k,所有元素之和为n。
三、思路分析
本人的思路:
与前面版本的区别是:选取的元素不重复,子集列表中的元素不重复。
上面是变化的地方,如不理解,请看本人前面版本的博客。
四、具体代码
本人的代码:
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
nums=[1,2,3,4,5,6,7,8,9]#构建数字列表
res=[]
self.dfs(nums,k,n,[],res)
return res
def dfs(self,nums,k,n,path,res):
if k==0 and n==0: #个数和所有元素之和都符合要求,添加子集列表。
res.append(path)
if n<0 or k<0:
return
for i in range(len(nums)):
self.dfs(nums[i+1:],k-1,n-nums[i],path+[nums[i]],res)
五、来源
题目连接:https://leetcode.com/problems/combination-sum-iii/
座右铭:站在别人的思想上,看见自己的不足,传播错误的经验,愿君不重蹈覆辙。
由于受限于本人经验,难免不足,如有建议,欢迎留言交流。
说明:这个类型题目的代码,本人都是在第一个别人写的代码上根据具体题目改编而来,所以第一个版本值得看看。
---------------------
作者:路漫漫,远修兮
来源:CSDN
原文:https://blog.csdn.net/qq_41827968/article/details/88756403
版权声明:本文为博主原创文章,转载请附上博文链接!