46. Permutations Leetcode Python

本文提供了一种高效的方法来生成一组数字的所有可能排列组合,并通过实例演示了实现过程。利用深度优先搜索(DFS)算法,我们可以在O(n!)的时间复杂度下生成所有排列,同时使用额外的O(n)空间来标记每个元素是否已被使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
        


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值