Python 如何从给定的列表范围生成所有可能的列表,该列表将以给定的输入和为目标

Python 如何从给定的列表范围生成所有可能的列表,该列表将以给定的输入和为目标,python,python-3.x,list,Python,Python 3.x,List,输入:目标和 输出:列表[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 _

输入:目标和

输出:列表[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))

根据@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))

希望这有帮助

欢迎来到StackOverFlow!看一看,什么是一个。您甚至可以在访问这些页面时获得奖励。我们不会为你写代码/做你的家庭作业。分享您迄今为止的尝试,我们将尝试改进。我在Python中尝试了这一点。您可以编辑您的帖子来添加此代码,更易于阅读的def combinationSum(self,candidates,target):rests=[[]用于范围内的(target)]对于候选项中的num:if num>target:continue else:rests[target-num].append([num])用于范围内的cur_rest(target-1,num-1,-1):对于rest[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))请按标签下的编辑按钮将此代码放入问题中。注释将丢失格式