46. Permutations
来源:互联网 发布:淘宝瑞士军刀包 编辑:程序博客网 时间:2024/05/17 06:58
题目
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]
]
思路
本题有两种思路,一种是DFS,每次两两交换,代码如下:
class Solution {public: vector<vector<int> > permute(vector<int> &num) { vector<vector<int> > res; permuteDFS(num, 0, res); return res; } void permuteDFS(vector<int> &num, int start, vector<vector<int> > &res) { if (start >= num.size()) res.push_back(num); for (int i = start; i < num.size(); ++i) { swap(num[start], num[i]); permuteDFS(num, start + 1, res); swap(num[start], num[i]); } }};
一种是网上公开的思路,思路如下:
当n=1时,数组中只有一个数a1,其全排列只有一种,即为a1
当n=2时,数组中此时有a1a2,其全排列有两种,a1a2和a2a1,那么此时我们考虑和上面那种情况的关系,我们发现,其实就是在a1的前后两个位置分别加入了a2
当n=3时,数组中有a1a2a3,此时全排列有六种,分别为a1a2a3, a1a3a2, a2a1a3, a2a3a1, a3a1a2, 和 a3a2a1。那么根据上面的结论,实际上是在a1a2和a2a1的基础上在不同的位置上加入a3而得到的。
_ a1 _ a2 _ : a3a1a2, a1a3a2, a1a2a3
_ a2 _ a1 _ : a3a2a1, a2a3a1, a2a1a3
代码如下:
class Solution {public: vector<vector<int> > permute(vector<int> &num) { if (num.empty()) return vector<vector<int> >(1, vector<int>()); vector<vector<int> > res; int first = num[0]; num.erase(num.begin()); vector<vector<int> > words = permute(num); for (auto &a : words) { for (int i = 0; i <= a.size(); ++i) { a.insert(a.begin() + i, first); res.push_back(a); a.erase(a.begin() + i); } } return res; }};
阅读全文
0 0
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 204. Count Primes
- Java知识:LinkedList类详解
- c# 发送和接受请求
- RabbitMQ基本概念简介
- 基蛋生物PLM项目正式进入实施阶段
- 46. Permutations
- Wireshark和Fiddler分析Android中的TLS协议包数据(附带案例样本)》》》原文链接
- Linux输入输出重定向及管道
- 那些机器“教”我的事儿
- 为什么总说程序员累成狗?
- idea建站遇见的小问题
- chrome 控制台 base64加密解密
- js读取设置cookies
- 数据结构的一些概念