zoukankan      html  css  js  c++  java
  • 【LeetCode】46. Permutations (2 solutions)

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

    解法一:递归

    class Solution {
    public:
        vector<vector<int> > permute(vector<int> &num) {
            vector<vector<int> > ret;
            Helper(ret, num, 0);
            return ret;
        }
        void Helper(vector<vector<int> >& ret, vector<int> num, int pos)
        {
            if(pos == num.size()-1)
                ret.push_back(num);
            else
            {
                for(int i = pos; i < num.size(); i ++)
                {//swap all the ints to the current position
                    swap(num[pos], num[i]);
                    Helper(ret, num, pos+1);
                    swap(num[pos], num[i]);
                }
            }
        }
    };

    解法二:just a joke

    别忘了先排序,因为next_permutation是升序返回的。

    class Solution 
    {
    public:
        vector<vector<int> > permute(vector<int> &num) 
        {
            vector<vector<int> > result;
            //sort first
            //note that next_permutation is in ascending order
            sort(num.begin(), num.end());
            result.push_back(num);
            while(next_permutation(num.begin(), num.end()))
            {
                result.push_back(num);
            }
            return result;
        }
    };

  • 相关阅读:
    子网掩码
    IP详解
    TCP/IP模型和OSI模型的对应
    Nginx模块之请求限制
    Nginx中的压力测试工具
    Nginx服务器的处理机制
    算法笔记-动态规划
    算法笔记-分治法
    算法笔记-贪心算法
    算法笔记-乱七八糟问题
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4161395.html
Copyright © 2011-2022 走看看