Given a collection of numbers, return all possible permutations.
For example,
[1,2,3] have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2],
and [3,2,1].
This problem is exponential. We can use one O(n) extra space to mark whether each element is used or not.
It is DFS.
class Solution:
# @param num, a list of integer
# @return a list of lists of integers
def bfs(self,num,val,res,used):
if len(val)==len(num) and val not in res:
res.append(val)
for i in range(len(num)):
if used[i]==False:
used[i]=True
val=val+[num[i]]
self.bfs(num,val,res,used)
val=val[:len(val)-1]
used[i]=False
def permute(self, num):
res=[]
if len(num)==0:
return res
used=[False]*len(num)
self.bfs(num,[],res,used)
return res
本文提供了一种高效的方法来生成一组数字的所有可能排列组合,并通过实例演示了实现过程。利用深度优先搜索(DFS)算法,我们可以在O(n!)的时间复杂度下生成所有排列,同时使用额外的O(n)空间来标记每个元素是否已被使用。
279

被折叠的 条评论
为什么被折叠?



