zoukankan      html  css  js  c++  java
  • 【LeetCode】Permutations

    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].

    code: STL method and recursion method.

     

    class Solution {
    public:
        vector<vector<int> > permute(vector<int> &num) {
            // Note: The Solution object is instantiated only once and is reused by each test case.
            vector<vector<int> > res;
            if(num.size() == 0) 
                return res;
            //vector<int> tmp;
            sort(num.begin(),num.end());
            res.push_back(num);
            while( next_permutation(num.begin(),num.end()) )
            {
                res.push_back(num);
            }
            return res;
        }
    };

    recursion vision:

     

    class Solution {
    public:
        
        vector<vector<int> > permute(vector<int> &num) {
            // Note: The Solution object is instantiated only once and is reused by each test case.
            vector<vector<int> > res;
            if(num.size() == 0) 
                return res;
            vector<int> tmp;
            sort(num.begin(),num.end());
            map<int,int> hash;
            permutation(0,num,res,hash,tmp);
            return res;
            
        }
        void permutation(int pos, vector<int> &num, vector<vector<int> > &res, map<int,int> &hash, vector<int> &tmp)
        {
            if(pos == num.size())
            {
                res.push_back(tmp);
                return ;
            }
            for(int i = 0; i < num.size(); i++)
            {
                if(hash[num[i]] != 1)
                {
                    tmp.push_back(num[i]);
                    hash[num[i]] = 1;
                    permutation(pos + 1, num, res, hash, tmp);
                    hash[num[i]] = 0;
                    tmp.pop_back();
                }
            }
            return ;
        }
        
    };


  • 相关阅读:
    spoj 104 Highways (最小生成树计数)
    bzoj 1912 巡逻(树直径)
    BZOJ 3534 重建
    BZOJ 3143 游走(高斯消元)
    在Windows下编译PyCaffe
    caffe的Matlab接口的使用方法
    NewRelic性能监控之APM
    MariaDB-10.x二进制包安装
    mongoDB-3.x Balancer Management
    mongoDB-3.x集群管理
  • 原文地址:https://www.cnblogs.com/keanuyaoo/p/3370800.html
Copyright © 2011-2022 走看看