# 077 combinations

### 77. Combinations

import itertools
p = [4, 8, 15, 16, 23, 42]
c = itertools.combinations(p, 4)
for i in c:
print i

(4, 8, 15, 16)
(4, 8, 15, 23)
(4, 8, 15, 42)
(4, 8, 16, 23)
(4, 8, 16, 42)
(4, 8, 23, 42)
(4, 15, 16, 23)
(4, 15, 16, 42)
(4, 15, 23, 42)
(4, 16, 23, 42)
(8, 15, 16, 23)
(8, 15, 16, 42)
(8, 15, 23, 42)
(8, 16, 23, 42)
(15, 16, 23, 42)


class Solution(object):
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
import itertools
return [list(i) for i in itertools.combinations(range(1,n+1), k)]


class Solution(object):
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
ans = []
self.dfs(n, k, 1, [], ans)
return ans

def dfs(self, n, k ,start, lst, ans):
if k == 0 :
ans.append(lst)
return
for i in range(start, n+1):
self.dfs(n, k - 1, i + 1,lst +[i], ans)



1          2     3
12  13 14    23 24   34


http://www.geeksforgeeks.org/print-all-possible-combinations-of-r-elements-in-a-given-array-of-size-n/

class Solution(object):
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
if k == 1:
return [[i + 1] for i in range(n)]
result = []
if n > k:
result = [r + [n] for r in self.combine(n - 1, k - 1)] + self.combine(n - 1, k)
else: #n == k
# result = [r + [n] for r in self.combine(n - 1, k - 1)]
result = [range(1,k+1)]
return result


apachecn/AiLearning