您的位置:首页 > 大数据 > 人工智能

leetcode_permutaionu全排列集合_31_46_47_60

2015-04-21 14:56 260 查看
这是leetcode上一个很有意思的排列集合

在此之前我想先引用leetcode上discuss里一位仁兄提出的问题:


use the function "STL next_permutation" to solve this problem. good or BAD???

其中最高票的回答是:

Definitely raise this concern to your interviewer before answering the question. It is good only when your interviewer says
so. However, it is verly likely that he or she will ask you to implement next_permutation all by yourself, so be prepared.


我觉得这也应该是我们对于重复造轮子的理解,无论是简单的为了应付面试还是加深自己的思维深度。

因此如果你的目标不仅仅是在题目列表前多加一个√:

It will make you more like a computer scientist,cheers!

所以在这里我会一次提供STL的解法和使用递归构造的解法。

传送门:

31https://leetcode.com/problems/next-permutation/

AC代码1:

class Solution {
public:
void nextPermutation(vector<int> &num) {
next_permutation(num.begin(),num.end());

}
};


46:https://leetcode.com/problems/permutations/

AC代码1:

具体思路是使得所有可能的集合都会出现。

class Solution {
public:
vector<vector<int> > permute(vector<int> &num) {
vector<vector<int> > ans;
sort(num.begin(),num.end());
do{
ans.push_back(num);
}while(next_permutation(num.begin(),num.end()));
return ans;

}
};


47:

传送门:https://leetcode.com/problems/permutations-ii/

具体思路是阻断所有重复的出现 / 允许出现但不加入最终的答案中。

AC代码1:

这道题所花费的时间在cpp里是最多的。

class Solution {
public:
bool check(vector<int> &num,vector<vector<int> > &ans)
{
for(int i=0;i<ans.size();i++)
if(num==ans[i]) return false;
return true;
}
vector<vector<int> > permuteUnique(vector<int> &num) {
vector<vector<int> > ans;
sort(num.begin(),num.end());
do{
if(check(num,ans))
ans.push_back(num);
}while(next_permutation(num.begin(),num.end()));
return ans;
}
};


60:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: