【问题标题】:How to generate all possible list from given range of list which will target given input sum如何从给定的列表范围生成所有可能的列表,这些列表将针对给定的输入总和
【发布时间】: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


【解决方案1】:

根据@Tomerikoo 建议的解决方案,我已经创建了一些修改的解决方案。

    def combinationSum(self, candidates, target):
        # List for storing possible all sequence of permutations
        seq_list = []

        # This loop will generate all possible permutation for given candidates
        for i in range(1, target + 1):
           # Extend given list with cartesian product of given candidates

           # To calculate cartesian product set use itertools.product with candidates
           # with set size ranging from 1 to target number
           # This is necessary as we have to find all possible combinations
           seq_list.extend([p for p in itertools.product(candidates, repeat=i)])

        # Just select those sequence whose sum is target
        result = [seq for seq in seq_list if sum(seq) == target]

        # Return length of result set
        return len(result)

s=Solution() 
c=[1,2,3] 
t=int(input()) 
print(s.combinationSum(c,t))

希望有帮助!!!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-15
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    • 2019-08-26
    • 2011-04-03
    相关资源
    最近更新 更多