zoukankan      html  css  js  c++  java
  • Leetcode题库——46.全排列


    @author: ZZQ
    @software: PyCharm
    @file: permute.py
    @time: 2018/11/15 19:42
    要求:给定一个没有重复数字的序列,返回其所有可能的全排列。
    示例:
    输入: [1,2,3]
    输出:
    [
    [1,2,3],
    [1,3,2],
    [2,1,3],
    [2,3,1],
    [3,1,2],
    [3,2,1]
    ]

    import copy
    
    """
    思路一: DFS,去掉不满足条件的排列
    """
    class Solution():
        def __init__(self):
            pass
    
        def permute(self, nums):
            """
            :type nums: List[int]
            :rtype: List[List[int]]
            """
            ans = []
            temp_ans = []
            length = len(nums)
            cur_length = 0
            self.dfs(temp_ans, nums, cur_length, length, ans)
            return ans
    
        def dfs(self, temp_ans, nums, cur_length, length, ans):
            if cur_length == length:
                tt_ans = copy.deepcopy(temp_ans)
                ans.append(tt_ans)
            else:
                for i in range(length):
                    if nums[i] not in temp_ans:
                        temp_ans.append(nums[i])
                        self.dfs(temp_ans, nums, cur_length+1, length, ans)
                        temp_ans.pop()
    
    """
    思路二: 交换元素+DFS
    """
    class Solution2():
        def __init__(self):
            pass
    
        def permute(self, nums):
            """
            :type nums: List[int]
            :rtype: List[List[int]]
            """
            nums_len = len(nums)
            ans = []
            if nums_len == 0 or nums == []:
                return []
            self.exchange(nums, 0, nums_len, ans) # 采用前后元素交换的办法,dfs解题
            return ans
    
        def exchange(self, nums, i, len, ans):
            if i == len-1:  # 将当前数组加到结果集中
                temp_list = []
                for j in range(len):
                    temp_list.append(nums[j])
                ans.append(temp_list)
                return
            # 将当前位置的数跟后面的数交换,并搜索解
            for j in range(i, len):
                temp = nums[i]
                nums[i] = nums[j]
                nums[j] = temp
                self.exchange(nums, i+1, len, ans)
                temp = nums[i]
                nums[i] = nums[j]
                nums[j] = temp
    
  • 相关阅读:
    在from表单中提交同name数据时,怎么获取所有值
    面试题
    String的创建模式
    spring的事务支持
    微信小程序+java实现附件上传以及下载打开详细过程记录
    spring编写AOP代理上的一点小坑
    java静态内部类的作用
    Python学习 :json、pickle&shelve 模块
    Python学习 :正则表达式
    Python学习 :常用模块(四)----- 配置文档
  • 原文地址:https://www.cnblogs.com/zzq-123456/p/9965988.html
Copyright © 2011-2022 走看看