LeetCode题解–46. Permutations
来源:互联网 发布:螨虫与痘痘的知乎 编辑:程序博客网 时间:2024/06/05 16:53
链接
LeetCode题目:https://leetcode.com/problems/permutations
难度:Medium
题目
Given a collection of distinct numbers, return all possible permutations.
生成n个数字的所有排列情况。
分析
为了生成n个数字的所有排列情况,可以先生成后面n-1个数字的所有排列情况,然后第1个数字插到任意位置。而生成n-1个数字的排列也可以先从生成n-2个数字开始,以此类推,最后生成1个数字的排列情况只需要返回该数字。
代码
class Solution {public: vector<vector<int>> permute(vector<int> &nums) { vector<vector<int>> res; for (int i = 0; i < nums.size(); i++) { vector<vector<int>> temp = permute2(nums, 0, i); for (auto x:temp) { res.push_back(x); } } return res; } vector<vector<int>> permute2(vector<int> &nums, int old_pos, int new_pos) { vector<vector<int>> res; if (nums.size() == 1) { res.push_back(nums); } else { vector<int> temp; for (int i = 0; i < old_pos; i++) { temp.push_back(nums[i]); } for (int i = old_pos + 1; i < nums.size(); i++) { temp.push_back(nums[i]); } auto all_permutes = permute(temp); for (auto x:all_permutes) { vector<int> temp2; int i, j; for (i = 0, j = 0; j < new_pos; i++, j++) { temp2.push_back(x[i]); } temp2.push_back(nums[old_pos]); for (; j < x.size(); i++, j++) { temp2.push_back(x[i]); } res.push_back(temp2); } } return res; }};
0 0
- LeetCode题解–46. Permutations
- LeetCode题解:Permutations
- LeetCode 题解(106): Permutations
- LeetCode题解——permutations
- LeetCode题解:Permutations I and II
- LeetCode 题解(107): Permutations II
- [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
- 关于使用引用类型所引起的错误
- 全排列(非递归)
- 2017移动互联网寒冬(Android)求职随感
- 一些图片过渡特效(C/C++)
- java零基础的外行人之(一) JAVA开发环境,基本类型,运算符
- LeetCode题解–46. Permutations
- 2016年11月起的新版Raspbian系统putty连接失败:Network error:Connection refused解决办法
- hive → phoenix数据导入导出方案
- 链表C++实现
- 把VIM打造成python开发环境
- jeecms 利用hover生成下拉菜单
- 图片解码播放器2
- ViewPager懒加载分析推荐
- 关于复杂语句和++的优先级