2013-12-16 111 views
0

我有n-raws m-columns矩陣,並且想要查找所有組合。例如:按列查找所有組合

2 5 6 9 
5 2 8 3 
1 1 9 4 
2 5 3 9 

我的程序將打印

2-5-6-9 
2-5-6-3 
2-5-6-4 
2-5-6-9 
2-5-8-9 
2-5-8-3... 

不能定義米×for循環。怎麼做?

回答

0

使用遞歸。爲每個位置指定哪些值可以在那裏(列)就足夠了,並且進行遞歸,該遞歸具有作爲傳遞位置的數字列表的參數。在遞歸迭代中迭代下一個位置的可能性。

Python實現:

def C(choose_numbers, possibilities): 
    if len(choose_numbers) >= len(possibilities): 
    print '-'.join(map(str, choose_numbers)) # format output 
    else: 
    for i in possibilities[len(choose_numbers)]: 
     C(choose_numbers+[i], possibilities) 

c = [[2, 5, 1, 2], [5, 2, 1, 5], [6, 8, 9, 3], [9, 3, 4, 9]] 
C([], c)