LeetCode | 46. Permutations
来源:互联网 发布:网民网络素养教育工作 编辑:程序博客网 时间:2024/05/21 15:12
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]]
题意:给出几个元素,生成这些元素的全排列。递归算法
//22 msclass Solution {public: int vis[1000000]; vector<vector<int> > res; void f(vector<int>& nums,vector<int>& tmp) { for(int i=0;i<nums.size();i++) { if(vis[i] == 0) //还没有放进去,压入 vector { tmp.push_back(nums[i]); vis[i] = 1; f(nums,tmp); vis[i] = 0; vector<int>::iterator it = tmp.end(); it--; tmp.erase(it); //删除刚才放进去的元素 } } if(tmp.size() == nums.size()) //全部都放进去了 { res.push_back(tmp); return; } } vector<vector<int>> permute(vector<int>& nums) { vector<int> tmp; f(nums,tmp); return res; }};
解法二:solution提供的解法,每次直接对现有数组交换顺序,不需要额外空间,代码量也更少
// 13 msclass Solution {public: vector<vector<int> > permute(vector<int> &num) { vector<vector<int> > result; permuteRecursive(num, 0, result); return result; } // permute num[begin..end] // invariant: num[0..begin-1] have been fixed/permuted void permuteRecursive(vector<int> &num, int begin, vector<vector<int> > &result) { if (begin >= num.size()) { // one permutation instance result.push_back(num); return; } for (int i = begin; i < num.size(); i++) { swap(num[begin], num[i]); permuteRecursive(num, begin + 1, result); // reset swap(num[begin], num[i]); } }};
阅读全文
1 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
- code[vs]2898 卢斯的进位制
- 对滚动视图contentInset自动设置场景的探讨
- Collectoin接口与Map接口的区别
- Java并发容器之阻塞队列简介
- 前端js性能测试工具(JSLitmus)的使用
- LeetCode | 46. Permutations
- android 以太网和wifi共存
- 用DeviceIoControl获取系统磁盘信息
- HDU 2966 KDtree模板
- php 使用 domxpath读写元素
- Spark SQL之queryExecution运行流程解析Logical Plan(三)
- 小M开发_MySql零基础_day170628
- 数据结构和算法
- php_screw 源码加密