博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode46. Permutations (思路及python解法)
阅读量:2241 次
发布时间:2019-05-09

本文共 619 字,大约阅读时间需要 2 分钟。

Given a collection of distinct integers, return all possible permutations.

Example:

Input: [1,2,3]Output:[  [1,2,3],  [1,3,2],  [2,1,3],  [2,3,1],  [3,1,2],  [3,2,1]]

一个深度优先遍历的应用。

深度优先遍历过程中的两个参数:nums记录剩余的数字,path记录已经按顺序选过的数字。

dfs过程中path+[nums[i]]不能用append的方式,会报错'NoneType' object has no attribute 'append'。

 

class Solution:    def permute(self, nums: List[int]) -> List[List[int]]:        final=[]        def dfs(nums, path):            if len(nums)==0:                final.append(path)            for i in range(len(nums)):                dfs(nums[:i]+nums[i+1:], path+[nums[i]])        dfs(nums,[])        return final

 

转载地址:http://kcrbb.baihongyu.com/

你可能感兴趣的文章
String常见面试题
查看>>
直插,快排,堆排,归并排序的分析
查看>>
二叉树的各种操作(面试必备)
查看>>
oracle
查看>>
泛型与通配符详解
查看>>
BaseServiceImpl中的实现关键点
查看>>
Struts2中的session、request、respsonse获取方法
查看>>
如何理解MVC模型
查看>>
SpringMVC中乱码解决方案
查看>>
SpringMVC中时间格式转换的解决方案
查看>>
post和get请求相关知识点
查看>>
关于try finally 中的return语句的问题
查看>>
RequestBody/ResponseBody处理Json数据
查看>>
springmvc请求参数获取的几种方法
查看>>
在eclipse中创建和myeclipse一样的包结构
查看>>
Java中的IO流
查看>>
java中的关键字
查看>>
如果某个方法是静态的,它的行为就不具有多态性
查看>>
优化Hibernate所鼓励的7大措施
查看>>
Java 8系列之重新认识HashMap
查看>>