1. 程式人生 > >組合演算法------非遞迴

組合演算法------非遞迴

 這種方法相當於每次從數組裡取一個元素和result裡的所有列表元素相加,列表元素里長度大於等於n的(挑選出n個數的組合)就沒有和元素相加的意義了,用不到。長度小於n的都會被用到,最後對result裡的元素過濾一下,只保留長度是n的。

def combination_add(num_list,n):
    result = [[]]
    for i in num_list:
        result.extend([[i]+x for x in result if len(x)<n])
    result = filter(lambda l:len(l)==n,result)
    print result