[LeetCode] Permutations
2015-06-02 23:09
246 查看
Well, have you solved the nextPermutation problem? If so, your code can be used in this problem. The idea is fairly simple:
sort
generate the next permutation of
repeat 2 until the next permutation of
The code is as follows.
A final note, the following code can be applied to the problem of Permutations II without any modification since the cases of duplicates have already been handled in
Of course, you are supposed to use the backtracking idea. A simple code is as follows.
sort
numsin ascending order, add it to
res;
generate the next permutation of
numsusing
nextPermutation(), and add it to
res;
repeat 2 until the next permutation of
numsreturns to the sorted condition in 1.
The code is as follows.
A final note, the following code can be applied to the problem of Permutations II without any modification since the cases of duplicates have already been handled in
nextPermutation(). If you want to learn more about
nextPermutation(), please visit this solution.
bool nextPermutation(vector<int>& nums) { int k = -1; for (int i = nums.size() - 2; i >= 0; i--) { if (nums[i] < nums[i + 1]) { k = i; break; } } if (k == -1) { sort(nums.begin(), nums.end()); return false; } int l = -1; for (int i = nums.size() - 1; i > k; i--) { if (nums[i] > nums[k]) { l = i; break; } } swap(nums[k], nums[l]); reverse(nums.begin() + k + 1, nums.end()); return true; } vector<vector<int>> permute(vector<int>& nums) { vector<vector<int> > res; sort(nums.begin(), nums.end()); res.push_back(nums); while (nextPermutation(nums)) res.push_back(nums); return res; }
Of course, you are supposed to use the backtracking idea. A simple code is as follows.
void permutate(vector<int> nums, int start, vector<vector<int> >& res) { if (start == nums.size()) { res.push_back(nums); return; } for (int i = start; i < nums.size(); i++) { swap(nums[i], nums[start]); permutate(nums, start + 1, res); } } vector<vector<int> > permute(vector<int>& nums) { vector<vector<int> > res; permutate(nums, 0, res); return res; }
相关文章推荐
- 在js中获取query string 以及重写URL的函数
- 4.2-2
- HDU 1166 线段树的单点更新 区间求和
- TortoiseSVN客户端重新设置用户名和密码
- 序列化
- Struts2原理图
- 由于 Web 服务器上的“ISAPI 和 CGI 限制”列表设置,无法提供您请求的页面。
- 请开启您PHP环境的openssl
- 欢迎使用CSDN-markdown编辑器
- HTML5 localStorage本地存储实际应用举例
- HTML5学习笔记 视频
- 课程改进建议
- Ubuntu 系统设置中不见了语言支持这个图标
- Ubuntu14.04建立WiFi热点
- HDOJ 1066 题解
- tcp 粘包
- jQuery css() 方法
- [LeetCode] Next Permutation
- 企业级负载平衡简介
- 缓存穿透与缓存雪崩