首页 > 其他 > 详细

LeetCode - Permutations

时间:2015-04-01 14:59:24      阅读:214      评论:0      收藏:0      [点我收藏+]

题目要求是找到一组数组的全排列

思路1:递归,在num中拿出1个数字放在第一个,然后剩下的数字做一个全排列

 1 class Solution {
 2 public:
 3     vector<vector<int> > permute(vector<int> &num) {
 4         int n = num.size();
 5         vector<vector<int> > ret;
 6         if (n == 0)
 7             return ret;
 8         if (n == 1)
 9         {
10             ret.push_back(num);
11             return ret;
12         }
13         vector<int> cur;
14         vector<int> tmp;
15         vector<vector<int> > post;
16         
17         //每次取1个数字
18         for (int i = 0; i < n; i++)
19         {
20             cur = num;
21             //剩下的数作全排列
22             cur.erase(cur.begin()+i);
23             post = permute(cur);
24             //将取出的数字放第一位
25             for (int j = 0; j < post.size(); j++)
26             {
27                 tmp = post[j];
28                 tmp.insert(tmp.begin(), num[i]);
29                 ret.push_back(tmp);
30             }
31         }
32         return ret;
33     }
34 };

 

LeetCode - Permutations

原文:http://www.cnblogs.com/bournet/p/4383799.html

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