【Leetcode】Permutations
2014-03-18 16:35
204 查看
Given a collection of numbers, return all possible permutations.
For example,
View Code
可以利用next permutation的方法,一个一个求,也可以用dfs的方法来求所有的排列。上面的代码是dfs版。
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> > result; sort(num.begin(), num.end()); vector<int> path; dfs(num, path, result); return result; } private: void dfs(vector<int> &num, vector<int> &path, vector<vector<int>> &result) { if (path.size() == num.size()) { result.push_back(path); return; } for (auto i : num) { if (find(path.begin(), path.end(), i) == path.end()) { path.push_back(i); dfs(num, path, result); path.pop_back(); } } } };
View Code
可以利用next permutation的方法,一个一个求,也可以用dfs的方法来求所有的排列。上面的代码是dfs版。
相关文章推荐
- “全排列”问题系列(一)[LeetCode] - 用交换元素法生成全排列及其应用,例题: Permutations I 和 II, N-Queens I 和 II,数独问题
- 算法分析与设计——LeetCode Problem.46 Permutations
- Permutations - Leetcode
- leetcode题集——permutations
- LeetCode-46-Permutations 暴力递归
- Leetcode Permutations II 最简单的解法
- Leetcode: Permutations
- LeetCode: Next Permutation & Permutations1,2
- Permutations leetcode
- LeetCode Permutations II
- Leetcode中的组合排列问题:Permutations,Combinations,Letter Combinations of a Phone Number
- LeetCode--Permutations 全排列
- [LeetCode] Permutations
- 【leetcode】Permutations
- Leetcode:Permutations
- Leetcode 46/47 Permutations, Permutations II
- leetcode之Permutations
- leetcode():Permutations
- LeetCode: Permutations
- LeetCode 46. Permutations