【Leetcode】Permutations

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].

 1 class Solution {
 2 public:
 3     vector<vector<int> > permute(vector<int> &num) {
 4         vector<vector<int> > result;
 5         sort(num.begin(), num.end());
 6         vector<int> path;
 7         dfs(num, path, result);
 8         return result;
 9     }
10 private:
11     void dfs(vector<int> &num, vector<int> &path, vector<vector<int>> &result) {
12         if (path.size() == num.size()) {
13             result.push_back(path);
14             return;
15         }
16         for (auto i : num) {
17             if (find(path.begin(), path.end(), i) == path.end()) {
18                 path.push_back(i);
19                 dfs(num, path, result);
20                 path.pop_back();
21             }
22         } 
23     }
24 };
View Code

可以利用next permutation的方法,一个一个求,也可以用dfs的方法来求所有的排列。上面的代码是dfs版。

posted @ 2014-03-18 16:35  小菜刷题史  阅读(168)  评论(0编辑  收藏  举报