[Leetcode]Permutations

来源:互联网 发布:徐州网络推广 编辑:程序博客网 时间:2024/06/16 08:20

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].

给出一个集合,要求返回它的所有排列~递归解法如下~

class Solution:    # @param num, a list of integer    # @return a list of lists of integers    def permute(self, num):        if num is None or len(num) == 0: return []        if len(num) == 1: return [num]        res = []        for i in xrange(len(num)):            for j in self.permute(num[:i] + num[i+1:]):                res.append([num[i]] + j)        return res
还有一种解法,也是用递归循环处理子问题,维护一个used数组来表示该元素是否已经存在当前结果中,每次取一个元素放入结果,然后递归剩下的元素~
class Solution:    # @param num, a list of integer    # @return a list of lists of integers    def permute(self, num):        if num is None or len(num) == 0: return []        self.res = []; used = [False] * len(num)         self.helper(num, used, [])        return self.res            def helper(self, num, used, item):        if len(item) == len(num):            self.res.append(item)            return        for i in xrange(len(num)):            if not used[i]:                used[i] = True                self.helper(num, used, item + [num[i]])                used[i] = False

还有非递归解法,可以参考http://blog.csdn.net/linhuanmars/article/details/21569031

0 0
原创粉丝点击