Cartesian product

A very simple algorithm. 

print the cartesian product of n sets

print_cartesian_product(list_of_sets): 

  out_set=set()

       print_cartesian_product(list_of_sets, out_set, 0)

print_cartesian_product(list_of_sets, out_set, i):

  if i == len(list_of_sets):

    //We have gone to the last set, now print out one combination. 

    for e in out_set: print(e)

    return

  for x in list_of_sets[i]:

    out_set.insert(x)

    print_cartesian_product(list_of_sets, out_set, i+1)

    out_set.remove(x)

 

Connection to print the combination number? 

Given a list of n elements, print all the possible combinations of k selections. 

//well, each element can either be selected or not selected, we can write the code similarly.

print_combination(list_elements, k):

  out_list=[]

  print_combinations(list_elements, k, 0, out_list) 

print_combinations(list_elements, k, cnt, out_list):

  if cnt==k:

    //we have arrived one combination, print

    for x in out_list: print(x)

    return

  for x in list_elements:

    out_list.append(x)

    print_combinations(list_elements, k, cnt+1, out_list)

    out_list.remove_last()

 

    

 

posted @ 2018-06-01 12:37  xxx's blog  阅读(303)  评论(0编辑  收藏  举报