【LeetCode】Permutations
2013-10-15 18:33
323 查看
Given a collection of numbers, return all possible permutations.
For example,
recursion vision:
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].
code: STL method and recursion method.
class Solution { public: vector<vector<int> > permute(vector<int> &num) { // Note: The Solution object is instantiated only once and is reused by each test case. vector<vector<int> > res; if(num.size() == 0) return res; //vector<int> tmp; sort(num.begin(),num.end()); res.push_back(num); while( next_permutation(num.begin(),num.end()) ) { res.push_back(num); } return res; } };
recursion vision:
class Solution { public: vector<vector<int> > permute(vector<int> &num) { // Note: The Solution object is instantiated only once and is reused by each test case. vector<vector<int> > res; if(num.size() == 0) return res; vector<int> tmp; sort(num.begin(),num.end()); map<int,int> hash; permutation(0,num,res,hash,tmp); return res; } void permutation(int pos, vector<int> &num, vector<vector<int> > &res, map<int,int> &hash, vector<int> &tmp) { if(pos == num.size()) { res.push_back(tmp); return ; } for(int i = 0; i < num.size(); i++) { if(hash[num[i]] != 1) { tmp.push_back(num[i]); hash[num[i]] = 1; permutation(pos + 1, num, res, hash, tmp); hash[num[i]] = 0; tmp.pop_back(); } } return ; } };
相关文章推荐
- LeetCode 46/47. Permutations i, ii
- [LeetCode]046-Permutations
- leetcode-Permutations(2014.2.3)
- LeetCode-46&47.Permutations
- 【Leetcode-Medium-46】Permutations
- LeetCode 46 Permutations
- LeetCode_46 Permutations
- leetcode Permutations II
- leetcode:Permutations1+2 + Rotat…
- [LeetCode]46. Permutations &&深搜DFS
- LeetCode——Permutations
- 【leetcode】Permutations
- leetcode 刷题之路 12 Permutations
- LeetCode - Permutations
- leetcode: Permutations
- LeetCode 46. Permutations
- Leetcode: Permutations
- Permutations -- LeetCode
- LeetCode 046 Permutations
- 47. Permutations II LeetCode