https://leetcode.com/problems/combinations/
这里的dfs tree: 见自己总结的notes
这题是经典的back tracking的题目。只要求出0,1全排列就行。利用backtracking的模板
这里的m是表示第m个元素
class Solution(object):
def dfs(self, m, k, nums, subres, res):
if sum(subres) == k:
res.append([nums[i] for i,c in enumerate(subres) if c == 1])
return
elif m >= len(nums):
return
else:
subres[m] = 0
self.dfs(m+1, k, nums, subres, res)
subres[m] = 1
self.dfs(m+1, k, nums, subres, res)
def combine(self, n, k):
""" :type n: int :type k: int :rtype: List[List[int]] """
nums = [x + 1 for x in xrange(n)]
subres = [0]*n
res = []
self.dfs(0, k, nums, subres,res)
return res
这里的dfs tree: 见自己总结的notes。 每个节点就是A数组的一个元素A[k],子节点(possible candidates)就是A[j], j>k
这里的start是表示第start个元素
pos表示现在的level
class Solution:
def dfs(self,pos,k,n,start,ans,vec):
if pos==k:
temp=vec[:]
ans.append(temp)
return
for i in range(start,n+1):
vec[pos]=i
self.dfs(pos+1,k,n,i+1,ans,vec)
# @return a list of lists of integers
def combine(self, n, k):
ans=[]
vec=[0 for i in range(k)]
self.dfs(0,k,n,1,ans,vec)
return ans
还有其他解法参考:
没有太理解。再看看
http://www.cnblogs.com/zuoyuan/p/3757165.html
https://www.zybuluo.com/chanvee/note/61530
http://oldoldb.com/MyCodeForLeetCode/2014/07/28/Combinations/
http://blog.csdn.net/whiterbear/article/details/49075645
关于backtracking:
http://www.cnblogs.com/wuyuegb2312/p/3273337.html
class Solution(object):
def dfs(self, depth, candidates, start, end, k, subres, res):
if depth == k:
res.append(subres)
i = start
while i < end:
self.dfs(depth + 1, candidates, i + 1, end, k, subres + [candidates[i]], res)
i += 1
def combine(self, n, k):
""" :type n: int :type k: int :rtype: List[List[int]] """
nums = [i + 1 for i in xrange(n)]
res = []
self.dfs(0, nums, 0, n, k, [], res)
return res