Python identify all the sum of n and k combinations, the combination may only contain a positive integer from 1-9, and repeatable number does not exist in each combination.

eg: Input: k = 3, n = 9

        Output: [[1,2,6], [1,3,5], [2,3,4]]

        Input: k = 2, n = 5

        Output: [[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

 

Published 35 original articles · won praise 26 · views 80000 +

Guess you like

Origin blog.csdn.net/weixin_42342968/article/details/99711035