Python 找出所有相加之和为n的k个组合,组合中只允许含有1-9的正整数,并且每种组合中不存在重复的数字。

eg:输入:k=3,n=9

        输出: [[1,2,6],[1,3,5],[2,3,4]]

        输入:k=2,n=5

        输出:[[1,4][2,3]]

------------------------------------------------------------------------------------

from itertools import combinations
def num(k,n):
    nums=[1,2,3,4,5,6,7,8,9]
    res=[]
    for i in range(len(nums)):
        res +=list(combinations(nums,i))
    res=[x for x in res if len(x) == k]
    a=[]
    for j in res:
        if sum(j) ==n :
            a.append(list(j))
    return a
发布了35 篇原创文章 · 获赞 26 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/weixin_42342968/article/details/99711035