leetcode_permutaionu全排列集合_31_46_47_60

这是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:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值