Find all subsets of length k in an array

前端 未结 13 1904
梦谈多话
梦谈多话 2020-11-27 05:34

Given a set {1,2,3,4,5...n} of n elements, we need to find all subsets of length k .

For example, if n = 4 and k = 2, the output would be

13条回答
  •  無奈伤痛
    2020-11-27 06:00

    This is python. Sorry for the spanish ;)

    from pprint import pprint
    conjunto = [1,2,3,4, 5,6,7,8,9,10]
    k = 3
    lista = []
    iteraciones = [0]
    def subconjuntos(l, k):
        if k == len(l):
            if not l in lista:
                lista.append(l)
            return
        for i in l:
            aux = l[:]
            aux.remove(i)
            result = subconjuntos(aux, k)
            iteraciones[0] += 1
            if not result in lista and result:
                lista.append( result)
    
    subconjuntos(conjunto, k)
    print (lista)
    print ('cant iteraciones: ' + str(iteraciones[0]))
    

提交回复
热议问题