【发布时间】:2019-07-12 20:59:09
【问题描述】:
输入:目标总和
输出:列表 [1,2,3] 中给定总和的所有可能排列的计数
示例输入:4 对应的输出:7
所有可能的配对:
1, 1, 1, 1
1, 2, 1
1, 1, 2
1, 3
2, 1, 1
2, 2
3, 1
对于这些用于解释输出的给定排列,对于任何输入,这些都必须取自[1,2,3]。
这是我迄今为止尝试过的:
def combinationSum(self, candidates, target):
rests = [[] for _ in range(target)]
for num in candidates:
if num > target:
continue
else:
rests[target - num].append([num])
for cur_rest in range(target - 1, num - 1, -1):
for result in rests[cur_rest]:
rests[cur_rest - num].append(result + [num])
return rests[0]
s=Solution()
c=[1,2,3]
t=int(input())
print(s.combinationSum(c,t))
【问题讨论】:
-
欢迎来到 StackOverFlow!看看How to create a Minimal, Reproducible Example 和什么是good question。您甚至会在访问这些页面时获得奖励。我们不会为您编写代码/做您的家庭作业。分享您到目前为止所尝试的内容,我们会努力改进它。
-
我在 python 中尝试过这个
-
您可以编辑您的帖子以添加此代码,更具可读性
-
def combinationSum(self, Candidates, target): rests = [[] for _ in range(target)] for num in Candidates: if num > target: continue else: rests[target - num] .append([num]) for cur_rest in range(target - 1, num - 1, -1): for result in rests[cur_rest]: rests[cur_rest - num].append(result + [num]) return rests[ 0] s=Solution() c=[1,2,3] t=int(input()) print(s.combinationSum(c,t))
-
请按标签下的
edit按钮将此代码放入您的问题中。评论失去格式
标签: python python-3.x list