leetcode | Permutations | 利用深度优先(DFS)的方法排列组合列表

来源:互联网 发布:博时基金公司知乎 编辑:程序博客网 时间:2024/05/16 01:44

Given a collection of distinct 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],  [3,2,1]]
即,给定一个列表(不重复),返回这个列表所有元素的排列组合。


class Solution(object):    def permute(self, nums):        res = []  #res 用于记录并返回所有排列组合。        self.excute(nums,[],res)        return res            def excute(self,nums,path,res): #path用于存放经过的元素        if not nums:            res.append(path)        for i in xrange(len(nums)):            self.excute(nums[:i]+nums[i+1:],path+[nums[i]],res) #每经过一个元素,将其从nums中取出,放入path,当nums为空时,就完成一个排列组合。



原创粉丝点击