首页 > 其他 > 详细

leetcode Permutations

时间:2014-10-29 01:54:58      阅读:147      评论: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].

求给定数的全排列。这里给定的数没有重复。所以用递归做。相应代码和解释如下。也可以学习这位大神的解法。

 1 class Solution {
 2 public:
 3     vector<vector<int> > permute(vector<int> &num)
 4     {
 5         vector<vector<int> > ans;
 6         if (num.size() == 1) // 这步是递归的关键,结束条件
 7             {ans.push_back(num);return ans;}
 8         
 9         vector<vector<int> > post;
10         vector<int> tmp;
11         vector<int> cur;
12         for (int i = 0; i < num.size(); ++i)
13         {
14             tmp = num;
15             tmp.erase(tmp.begin() + i); // 把num中的相应位置的数先去掉
16             post = permute(tmp);// 得到剩下的其他数字的结果在post中
17             for (int j = 0; j < post.size(); ++j)//在post的每个结果前面加上刚才去掉的值就可以得到解了
18             {
19                 cur = post[j];
20                 cur.insert(cur.begin(), num[i]);
21                 ans.push_back(cur);
22             }
23         }
24         return ans;
25     }
26 };

 

leetcode Permutations

原文:http://www.cnblogs.com/higerzhang/p/4058356.html

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