【发布时间】:2016-06-28 17:32:08
【问题描述】:
我正在尝试通过遵循包含或不包含每个递归调用的元素的策略,递归地生成列表的所有 n 选择 k 组合(不检查唯一性)。我绝对可以打印出组合,但我一生无法弄清楚如何在 Python 中返回正确的列表。以下是一些尝试:
class getCombinationsClass:
def __init__(self,array,k):
#initialize empty array
self.new_array = []
for i in xrange(k):
self.new_array.append(0)
self.final = []
self.combinationUtil(array,0,self.new_array,0,k)
def combinationUtil(self,array,array_index,current_combo, current_combo_index,k):
if current_combo_index == k:
self.final.append(current_combo)
return
if array_index >= len(array):
return
current_combo[current_combo_index] = array[array_index]
#if current item included
self.combinationUtil(array,array_index+1,current_combo,current_combo_index+1,k)
#if current item not included
self.combinationUtil(array,array_index+1,current_combo,current_combo_index,k)
在上面的示例中,我尝试将结果附加到似乎不起作用的外部列表中。我还尝试通过递归构造一个最终返回的列表来实现这一点:
def getCombinations(array,k):
#initialize empty array
new_array = []
for i in xrange(k):
new_array.append(0)
return getCombinationsUtil(array,0,new_array,0,k)
def getCombinationsUtil(array,array_index,current_combo, current_combo_index,k):
if current_combo_index == k:
return [current_combo]
if array_index >= len(array):
return []
current_combo[current_combo_index] = array[array_index]
#if current item included & not included
return getCombinationsUtil(array,array_index+1,current_combo,current_combo_index+1,k) + getCombinationsUtil(array,array_index+1,current_combo,current_combo_index,k)
当我对列表 [1,2,3] 和 k = 2 进行测试时,对于这两种实现,我不断得到结果 [[3,3],[3,3],[3,3 ]]。但是,如果我在内部 (current_combo_index == k) if 语句中实际打印出“current_combo”变量,则会打印出正确的组合。是什么赋予了?我误解了与变量范围或 Python 列表有关的事情?
【问题讨论】:
标签: python algorithm list recursion combinations