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], ]
组合问题。适合使用回溯法解决,另外python下地itertools中也提供了combinations函数。
回溯法:
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 not k: ans.append(lst) return for i in range(start, n + 1): self.dfs(n, k - 1, i + 1, lst + [i], ans)
itertools.combinations:
class Solution(object): def combine(self, n, k): """ :type n: int :type k: int :rtype: List[List[int]] """ from itertools import combinations return [list(c) for c in 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 = [] stack = [] x = 1 while True: l = len(stack) print stack, x, 2 + l if l == k: ans.append(stack[:]) if l == k or x > n - k + l + 1: if not stack: return ans x = stack.pop() + 1 else: stack.append(x) x += 1
代码解释:Combinations is typical application for backtracking. Two conditions for back track: (1) the stack length is already k (2) the current value is too large for the rest slots to fit in since we are using ascending order to make sure the uniqueness of each combination.
我的翻译:Combinations是典型的适用回溯法的题型。该代码会在满足两种条件下回溯:(1)当栈的长度已经达到k了;(2)当前值太大,无法放入栈中(由于是升序添加元素,所以可以确保每次产生的解不重复)。