首页 > 其他 > 详细

【Leetcode】Permutations

时间:2014-03-19 08:23:44      阅读:446      评论:0      收藏:0      [点我收藏+]

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

bubuko.com,布布扣
 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版。

【Leetcode】Permutations,布布扣,bubuko.com

【Leetcode】Permutations

原文:http://www.cnblogs.com/dengeven/p/3608081.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!