【LeetCode】46. Permutations 解题报告(Python & C++)
- 作者: 负雪明烛
- id: fuxuemingzhu
- 个人博客:http://fuxuemingzhu.cn/
题目地址: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++)的更多相关文章
- 【LeetCode】Permutations 解题报告
全排列问题.经常使用的排列生成算法有序数法.字典序法.换位法(Johnson(Johnson-Trotter).轮转法以及Shift cursor cursor* (Gao & Wang)法. ...
- LeetCode: Combination Sum 解题报告
Combination Sum Combination Sum Total Accepted: 25850 Total Submissions: 96391 My Submissions Questi ...
- LeetCode: Permutations 解题报告
Permutations Given a collection of numbers, return all possible permutations. For example,[1,2,3] ha ...
- 【LeetCode】94. Binary Tree Inorder Traversal 解题报告(Python&C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 解题方法 递归 迭代 日期 题目地址:https://leetcode.c ...
- LeetCode - Course Schedule 解题报告
以前从来没有写过解题报告,只是看到大肥羊河delta写过不少.最近想把写博客的节奏给带起来,所以就挑一个比较容易的题目练练手. 原题链接 https://leetcode.com/problems/c ...
- LeetCode - 46. Permutations
46. Permutations Problem's Link -------------------------------------------------------------------- ...
- LeetCode: Sort Colors 解题报告
Sort ColorsGiven an array with n objects colored red, white or blue, sort them so that objects of th ...
- 【LeetCode】107. Binary Tree Level Order Traversal II 解题报告 (Python&C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:DFS 方法二:迭代 日期 [LeetCode ...
- 【LeetCode】206. Reverse Linked List 解题报告(Python&C++&java)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 迭代 递归 日期 [LeetCode] 题目地址:h ...
随机推荐
- Linux服务器I/O性能分析-2
一.如何正确分析IO性能 1.1 BLKTRACE分析IO性能 之前的文章已经说明,要是系统发生I/O性能问题,我们常用的命令是无法精确定位问题(内核I/O调度器消耗的时间和硬件消耗的时间,这个不能作 ...
- cp -拷贝文件出现错误
对于cp -a最主要的用法是在保留原文件属性的前提下复制文件. 如果出现了拷贝文件错误,在文件前面加上-a 即可
- c#表格序号列
<asp:BoundField HeaderText="序号" /> OnRowCreated="gridview_RowCreated" prot ...
- Kubernetes:应用自动扩容、收缩与稳定更新
在前面我们已经学习到了 Pod 的扩容.滚动更新等知识,我们可以手动为 Deployment 等设置 Pod 副本的数量,而这里会继续学习 关于 Pod 扩容.收缩 的规则,让 Pod 根据节点服务器 ...
- MapReduce05 框架原理OutPutFormat数据输出
目录 4.OutputFormat数据输出 OutputFormat接口实现类 自定义OutputFormat 自定义OutputFormat步骤 自定义OutputFormat案例 需求 需求分析 ...
- 大数据学习day28-----hive03------1. null值处理,子串,拼接,类型转换 2.行转列,列转行 3. 窗口函数(over,lead,lag等函数) 4.rank(行号函数)5. json解析函数 6.jdbc连接hive,企业级调优
1. null值处理,子串,拼接,类型转换 (1) 空字段赋值(null值处理) 当表中的某个字段为null时,比如奖金,当你要统计一个人的总工资时,字段为null的值就无法处理,这个时候就可以使用N ...
- Sharding-JDBC 简介
什么是Sharding-JDBC 1.是轻量级的 java 框架,是增强版的 JDBC 驱动2. Sharding-JDBC(1)主要目的是:简化对分库分表之后数据相关操作.不是帮我们做分库分表,而是 ...
- 案例 stm32的dma传输过程
首先说一下:DMA_GetCurrDataCounter返回值是什么 返回值是dma缓存里还剩余多少空间. 上面本来应该是,发一下,改变一下.但是这里有一行是特殊的. long : 461,*ff l ...
- 使用$.post方式来实现页面的局部刷新功能
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...
- AD小白如何发板厂制板--导出gerber文件和钻孔文件+嘉立创下单教程
AD如何发工程制板子? 方式1,发PCB源文件给板厂 方式2,发一些工艺文件给板厂,这样就无须泄漏你的PCB源文件了,一个硬件工程师必须要掌握方式2. 方式2要做的就是导出gerber文件和钻孔文件, ...