【LeetCode】46. Permutations (2 solutions)
2014-12-13 14:49
148 查看
Permutations
Given a collection of numbers, return all possible permutations.
For example,
解法一:递归
解法二:just a joke
别忘了先排序,因为next_permutation是升序返回的。
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].
解法一:递归
class Solution { public: vector<vector<int> > permute(vector<int> &num) { vector<vector<int> > ret; Helper(ret, num, 0); return ret; } void Helper(vector<vector<int> >& ret, vector<int> num, int pos) { if(pos == num.size()-1) ret.push_back(num); else { for(int i = pos; i < num.size(); i ++) {//swap all the ints to the current position swap(num[pos], num[i]); Helper(ret, num, pos+1); swap(num[pos], num[i]); } } } };
解法二:just a joke
别忘了先排序,因为next_permutation是升序返回的。
class Solution { public: vector<vector<int> > permute(vector<int> &num) { vector<vector<int> > result; //sort first //note that next_permutation is in ascending order sort(num.begin(), num.end()); result.push_back(num); while(next_permutation(num.begin(), num.end())) { result.push_back(num); } return result; } };
相关文章推荐
- LeetCode Solutions : Rotate List
- 【LeetCode】145. Binary Tree Postorder Traversal (3 solutions)
- 【LeetCode】258. Add Digits (2 solutions)
- 【LeetCode】Valid Anagram (2 solutions)
- 【LeetCode】40. Combination Sum II (2 solutions)
- 【LeetCode】25. Reverse Nodes in k-Group (2 solutions)
- 【LeetCode】206. Reverse Linked List (2 solutions)
- 【LeetCode】144. Binary Tree Preorder Traversal (3 solutions)
- 【LeetCode】162. Find Peak Element (3 solutions)
- 【LeetCode】142. Linked List Cycle II (2 solutions)
- 【LeetCode】48. Rotate Image (2 solutions)
- 【LeetCode】111. Minimum Depth of Binary Tree (2 solutions)
- 【LeetCode】75. Sort Colors (3 solutions)
- 【LeetCode】173. Binary Search Tree Iterator (2 solutions)
- 【LeetCode】14. Longest Common Prefix (2 solutions)
- 【LeetCode】102. Binary Tree Level Order Traversal (2 solutions)
- 【LeetCode】24. Swap Nodes in Pairs (3 solutions)
- 【LeetCode】80. Remove Duplicates from Sorted Array II (2 solutions)
- 【LeetCode】136. Single Number (4 solutions)
- 【LeetCode】230. Kth Smallest Element in a BST (2 solutions)