题目地址:https://leetcode.com/problems/permutations/description/

题目描述

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

解题方法

方法一:库函数

使用python自带的permutations函数,直接进行全排列。

from itertools import permutations
class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
return list(permutations(nums))

C++中也有next_permutation函数,但是注意需要先排序。

class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> res;
sort(nums.begin(), nums.end());
do {
res.push_back(nums);
} while (next_permutation(nums.begin(), nums.end()));
return res;
}
};

方法二:递归

如果仔细观察题目全排列的输出结果就会发现,所谓全排列就是以每个nums中每个数字为起始位置,将剩余的数字全排列。所以可以使用递归求解。

想解决递归问题,必须对函数的定义十分了解。代码中定义的dfs()是对nums进行全排列,已有的排列结果放到path中,当nums为空时说明递归完成,把path放入res中。

Python代码如下:

class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
self.dfs(nums, res, [])
return res def dfs(self, nums, res, path):
if not nums:
res.append(path)
else:
for i in xrange(len(nums)):
self.dfs(nums[:i] + nums[i + 1:], res, path + [nums[i]])

方法三:回溯法

回溯法是解决排列问题的经典方法,速度也能明显加快。

回溯法的含义是对每个可能的结果进行遍历,如果某个数字已经使用则跳过,如果没有使用则放入path中。这个“回溯”怎么理解?我认识是在递归的过程中使用了一个数组path来保存自己走过的路,如果沿着这条路走完了全部的解,则需要弹出path中的最后一个元素,相当于向后回退,于是叫做回溯法。

下面的做法中,使用了visited数组来保存是否经历过这个位置。

C++版本的代码如下:

class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
const int N = nums.size();
vector<vector<int>> res;
vector<int> path;
vector<int> visited(N, 0);
dfs(nums, 0, visited, res, path);
return res;
}
private:
void dfs(vector<int>& nums, int pos, vector<int>& visited, vector<vector<int>>& res, vector<int>& path) {
const int N = nums.size();
if (pos == N) {
res.push_back(path);
return;
}
for (int i = 0; i < N; i++) {
if (!visited[i]) {
visited[i] = 1;
path.push_back(nums[i]);
dfs(nums, pos + 1, visited, res, path);
path.pop_back();
visited[i] = 0;
}
}
}
};

Python代码如下:

class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
visited = [0] * len(nums)
res = [] def dfs(path):
if len(path) == len(nums):
res.append(path)
else:
for i in range(len(nums)):
if not visited[i]:
visited[i] = 1
dfs(path + [nums[i]])
visited[i] = 0 dfs([])
return res

日期

2018 年 2 月 24 日
2018 年 12 月 14 日 —— 12月过半,2019就要开始
2019 年 9 月 25 日 —— 做梦都在秋招,这个秋天有毒

【LeetCode】46. Permutations 解题报告(Python & C++)的更多相关文章

  1. 【LeetCode】Permutations 解题报告

    全排列问题.经常使用的排列生成算法有序数法.字典序法.换位法(Johnson(Johnson-Trotter).轮转法以及Shift cursor cursor* (Gao & Wang)法. ...

  2. LeetCode: Combination Sum 解题报告

    Combination Sum Combination Sum Total Accepted: 25850 Total Submissions: 96391 My Submissions Questi ...

  3. LeetCode: Permutations 解题报告

    Permutations Given a collection of numbers, return all possible permutations. For example,[1,2,3] ha ...

  4. 【LeetCode】94. Binary Tree Inorder Traversal 解题报告(Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 解题方法 递归 迭代 日期 题目地址:https://leetcode.c ...

  5. LeetCode - Course Schedule 解题报告

    以前从来没有写过解题报告,只是看到大肥羊河delta写过不少.最近想把写博客的节奏给带起来,所以就挑一个比较容易的题目练练手. 原题链接 https://leetcode.com/problems/c ...

  6. LeetCode - 46. Permutations

    46. Permutations Problem's Link -------------------------------------------------------------------- ...

  7. LeetCode: Sort Colors 解题报告

    Sort ColorsGiven an array with n objects colored red, white or blue, sort them so that objects of th ...

  8. 【LeetCode】107. Binary Tree Level Order Traversal II 解题报告 (Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:DFS 方法二:迭代 日期 [LeetCode ...

  9. 【LeetCode】206. Reverse Linked List 解题报告(Python&C++&java)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 迭代 递归 日期 [LeetCode] 题目地址:h ...

随机推荐

  1. ui自动化测试,页面方法的使用

    悬浮下拉框 的设置选择 下拉框的选择 显性等待 双击, ActionChains类的方法行动链 提示框 双击,右击 双击用到行动连,提示框用到Alert的类 右击用到的也是行动连 UI自动化测试 #h ...

  2. Flink 实践教程-进阶(2):复杂格式数据抽取

    作者:腾讯云流计算 Oceanus 团队 流计算 Oceanus 简介 流计算 Oceanus 是大数据产品生态体系的实时化分析利器,是基于 Apache Flink 构建的具备一站开发.无缝连接.亚 ...

  3. c#年份筛选

    年份: <script type="text/javascript" src="http://www.shicishu.com/down/WdatePicker.j ...

  4. Spark集群环境搭建——服务器环境初始化

    Spark也是属于Hadoop生态圈的一部分,需要用到Hadoop框架里的HDFS存储和YARN调度,可以用Spark来替换MR做分布式计算引擎. 接下来,讲解一下spark集群环境的搭建部署. 一. ...

  5. 零基础学习java------day17------缓冲字节流,转换字节流,简化流,缓冲字符流,序列化和对象流

    1. 缓冲字节流 缓冲区:缓冲区实质上是一个数组.通常它是一个字节数组,但是也可以使用其他种类的数组.但是一个缓冲区不 仅仅 是一个数组.缓冲区提供了对数据的结构化访问,而且还可以跟踪系统的读/写进程 ...

  6. 淘宝、网易移动端 px 转换 rem 原理,Vue-cli 实现 px 转换 rem

       在过去的一段时间里面一直在使用Vue配合 lib-flexible和px2rem-loader配合做移动端的网页适配.秉着求知的思想,今天决定对他的原理进行分析.目前网上比较主流使用的就是淘宝方 ...

  7. fastjson转换数字时,格式化小数点

    使用fastjson类库转换java对象时,对于BigDecimal类型,有时需要特殊格式,比如: 1.0,转为json时候,要求显式为1,因此需要在转换时做处理.步骤如下: 1.新建类,实现Valu ...

  8. JVM——垃圾收集算法及垃圾回收器

    一.垃圾回收算法 1.标记-清除算法 1)工作流程 算法分为"标记"和"清除"阶段:首先标记出所有需要回收的对象(标记阶段),在标记完成后统一回收所有被标记的对 ...

  9. Android 高级UI组件(三)

    一.popupWindow 1.AlertDialog和PopupWindow最关键的区别是AlertDialog不能指定显示位置,只能默认显示在屏幕最中间(当然也可以通过设置WindowManage ...

  10. 1.Java语言基础

    一:java语言介绍 (1). 1991年出现,1995年5月正式发布 出生地:SUN  创始人:James Gosling  2009年4月被Oracle收购 目前最新的版本2018年3月v10.0 ...