LeetCode --- 46. Permutations
来源:互联网 发布:网络被高智慧生物屏蔽 编辑:程序博客网 时间:2024/05/16 00:51
题目链接:Permutations
Given a collection of 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], and [3,2,1].
这道题的要求是给定一组数字,生成所有的排列组合。
1. 递归排列
这是一个排列的问题,首先联想到的就是递归方式。每次逐个固定每个元素到第一位置,然后递归排列剩下的元素。当固定到前面的元素数量等于数组长度的时候,递归终止。
时间复杂度:O(n!)(结果数量)
空间复杂度:O(n!)
1 class Solution 2 { 3 public: 4 vector<vector<int> > permute(vector<int> &num) 5 { 6 vector<vector<int> > vvi; 7 permute(num, 0, vvi); 8 return vvi; 9 }10 private:11 void permute(vector<int> &num, int i, vector<vector<int> > &vvi)12 {13 if(i == num.size())14 {15 vvi.push_back(num);16 return;17 }18 for(int j = i; j < num.size(); ++ j)19 {20 swap(num[i], num[j]);21 permute(num, i + 1, vvi);22 swap(num[i], num[j]);23 }24 }25 };
2. next_permutation
其实还可以利用next_permutation()函数,逐步生成下一个排列。由于next_permutation()在最后一个排列时返回false,因此可以先对数组排序,然后调用next_permutation()直到其返回false。
时间复杂度:O(n!)(结果数量)
空间复杂度:O(n!)
1 class Solution 2 { 3 public: 4 vector<vector<int> > permute(vector<int> &num) 5 { 6 sort(num.begin(), num.end()); 7 8 vector<vector<int> > vvi({num}); 9 while(next_permutation(num.begin(), num.end()))10 vvi.push_back(num);11 12 return vvi;13 }14 };
转载请说明出处:LeetCode --- 46. Permutations
0 0
- [LeetCode]46.Permutations
- LeetCode 46.Permutations
- 46. Permutations Leetcode Python
- LeetCode --- 46. Permutations
- [Leetcode] 46. Permutations
- [leetcode] 46.Permutations
- LeetCode 46. Permutations DFS
- 46. Permutations LeetCode
- Leetcode 46. Permutations
- leetcode 46. Permutations
- LeetCode *** 46. Permutations
- LeetCode 46. Permutations
- leetcode 46. Permutations
- LeetCode - 46. Permutations
- 【leetcode】46. Permutations
- leetcode 46. Permutations
- [LeetCode] 46. Permutations
- leetcode 46. Permutations
- oracle查看数据库锁表情况
- 如何学好一门编程语言或技术?
- Visio安装失败 无法打开注册表项 解决方案
- centos中源码编译nginx
- 如何让自己内心宁静平和?
- LeetCode --- 46. Permutations
- SQL 遍历父子关系表(二叉树)获得所有子节点 所有父节点(转)
- Gson Jackson JSON-lib 性能比较
- 数据库连接
- 每一天都这么干:(1)打篮球40个
- operator
- plsql 常用函数
- mysql/mariadb 使用数据库名.表名更新 主从不同步的一个问题
- oracle查询表空间的大小