leetcode Permutations
来源:互联网 发布:mysql union order 编辑:程序博客网 时间:2024/06/08 18:47
废话少说,先上题:
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]
.
解这题的思路是从数组中找一个数作为第一位,然后依次找下一位作为permuta的第二位,我这里采用的是找到一位就把那位从数组中删除,判断数组为空的时候推、退出递归。上代码(accept):
class Solution {public:void dfs(vector<vector<int> >& result, vector<int>& tmp, vector<int>& num){if (num.empty()){result.push_back(tmp);return;}for (int i = 0; i < num.size(); i++){tmp.push_back(num[i]);auto iter = num.begin();iter += i;vector<int> tmpA = num;num.erase(iter);dfs(result, tmp, num);num = tmpA;tmp.pop_back();}}vector<vector<int> > permute(vector<int> &num){vector<vector<int> > result;if (num.empty()){return result;}vector<int> tmp;dfs(result, tmp, num);return result;}};以前我是用next_permutation的算法做的,就是循环n!次next_permutation,也能accept,同样上代码:
class Solution {public: void nextPermutation(vector<int> &num) { if (num.empty() || num.size() == 1) { return; } auto iter = num.end() - 1; for (; iter != num.begin(); iter--) { if (*iter > *(iter - 1)) { break; } } if (iter == num.begin()) { reverse(num.begin(), num.end()); return; } else { if (iter == num.end() - 1) { swap(num[iter - num.begin()], num[iter - num.begin() - 1]); return; } else { auto it = iter; while (*(it + 1) > *(iter - 1) && it != num.end() - 1) { it++; } swap(num[it - num.begin()], num[iter - num.begin() - 1]); sort(iter, num.end()); return; } } } int factoral(int n) { int nRet = 1; for (int i = 1; i <= n; i++) { nRet *= i; } return nRet; } vector<vector<int> > permute(vector<int> &num) { vector<vector<int>> result; vector<int> tmp = num; result.push_back(tmp); int n = num.size(); int size = factoral(n); for (int i = 0; i < size - 1; i++) { nextPermutation(tmp); result.push_back(tmp); } return result; }};
0 0
- 【LeetCode】Permutations && Permutations II
- leetcode: Permutations/Permutations II
- leetcode Permutations & Permutations II
- [Leetcode]Permutations && Permutations II
- LeetCode: Permutations
- LeetCode: Permutations
- [Leetcode] Permutations
- [LeetCode] Permutations
- Leetcode: Permutations
- [Leetcode] Permutations
- [Leetcode] Permutations
- [LeetCode]Permutations
- LeetCode-Permutations
- [leetcode] permutations
- LeetCode - Permutations
- Leetcode: Permutations
- 【leetcode】Permutations
- 【LeetCode】Permutations
- 三 迭代器(iterator)概念与traits编程技法
- 平摊分析
- PHPUML 生成UML
- cocos2d-x基本知识点(5)
- ruby on rails 上传gem
- leetcode Permutations
- poj 1028 False coin
- alter table move跟shrink space的区别
- Fedora开启ssh服务
- 1、Extjs——ExtJs简介
- Fragment与Activity的通信(回调),Fragment间的通信
- siege 压力测试
- socket阻塞与非阻塞,同步与异步、I/O模型
- asp.net中的按钮在页面上有验证控件的时候不触发按钮事件