您的位置:首页 > 其它

leetcode -- Combination -- 重点,求可能的0,1全排列

2015-12-13 21:19 309 查看
https://leetcode.com/problems/combinations/

思路1: 枚举0,1全排列。

这里的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


思路2:另一种组合树

这里的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


还有其他解法参考:

没有太理解。再看看

/article/4982550.html

https://www.zybuluo.com/chanvee/note/61530

http://oldoldb.com/MyCodeForLeetCode/2014/07/28/Combinations/

/article/2219404.html

关于backtracking:

/article/4935263.html

自己重写code

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: