zoukankan      html  css  js  c++  java
  • LeetCode OJ--Permutations *

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

    写出一列数的全排列

    #include <iostream>
    #include <vector>
    #include <algorithm>
    using namespace std;
     
    class Solution{
    public:
        vector<vector<int> > permute(vector<int> &num) {
           vector<vector<int> > ans;
           if(num.size()==0)
               return ans;
    
           vector<int> _num = num;
           sort(_num.begin(),_num.end());
    
           ans.push_back(_num);
           while(nextPermutation(_num))
           {
               ans.push_back(_num);
           }
           return ans;
        }
    private:
        bool nextPermutation(vector<int> &num)
        {
            return next_permutation(num.begin(),num.end());
        }
    
        template<typename BidiIt>
        bool next_permutation(BidiIt first,BidiIt last)
        {
            const auto rfirst = reverse_iterator<BidiIt>(last);
            const auto rlast = reverse_iterator<BidiIt>(first);
    
            auto pivot = next(rfirst);
            while(pivot != rlast && *pivot >= *prev(pivot))
            {
                ++pivot;
            }
            
            //this is the last permute, or the next is the same as the begin one
            if(pivot == rlast)
            {
                reverse(rfirst,rlast);
                return false;
            }
            //find the first num great than pivot
            auto change = rfirst;
            while(*change<=*pivot)
                ++change;
    
            swap(*change,*pivot);
            reverse(rfirst,pivot);
            return true;
        }
    };
    
    int main()
    {
        vector<int> num;
        num.push_back(9);
        num.push_back(8);
        num.push_back(5);
         
        Solution myS;
        myS.permute(num);
        return 0;
    }
  • 相关阅读:
    node 父子进程传递对象
    js 按照字母进行分组
    native react 代码智能提示
    VScode 使用emmet
    c# webapi swagger
    c# 前台和后台线程
    Java——字节和字符的区别
    Java——类的访问修饰符
    Java——面向对象
    Java——内存中的数组
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3784562.html
Copyright © 2011-2022 走看看