#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Combinations:Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
For example,
If n = 4 and k = 2, a solution is:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4], #左侧的数字要大于右侧
]
'''
class Solution(object):
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
if k > n:
return []
ret = []
self.__combine(n,k,1,0,range(k),ret)
return ret
def __combine(self,n,k,start_num,start_index,tmp,ret):
if n - start_num + 1 < k - start_index:#小优化,如果剩余的数字的个数 < 要填充的个数,直接返回就好
return
if start_index == k:
return ret.append(list(tmp))
for i in range(start_num,n+1):
tmp[start_index] = i
self.__combine(n,k,i + 1,start_index + 1,tmp,ret)#右侧数字大于左侧数字,所以填充下一位时从左侧+1处开始即可
if __name__ == "__main__":
s = Solution()
print s.combine(4,2)
34 leetcode - Combinations
最新推荐文章于 2025-08-13 21:50:19 发布