Leetcode 46. Permutations 和Leetcode 47. Permutations II

版权声明:本文为博主原创文章,如要转载请在转载的文章后附上本人博客链接! https://blog.csdn.net/syyyy712/article/details/81162377

本文中这两题全排列的解法采用了STL中的函数next_permutation(),其返回值是布尔类型,next_permutation()函数是寻找当前排列之后的下一个排列,比如[1,2,3]后面的是[1,3,2],当找到[3,2,1]时发现没有下一个排列就会返回false。另外还有一个函数是prev_permutation(),该函数是寻找当前排列的前一个排列,比如当前排列是[1,3,2],那么前一个排列是[1,2,3],当找到[1,2,3]时发现没有前一个排列了,因此返回false。
注意一点的是这两个函数均会从当前排列开始寻找,区别在于往上找还是往下找。


46题题目描述:
Given a collection of distinct integers, return all possible permutations.

Example:

Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]

C++代码:

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


47题题目描述:
Given a collection of numbers that might contain duplicates, return all possible unique permutations.

Example:

Input: [1,1,2]
Output:
[
[1,1,2],
[1,2,1],
[2,1,1]
]

C++代码:

class Solution {
public:
    vector<vector<int>> permuteUnique(vector<int>& nums) 
    {
        sort(nums.begin(),nums.end());
        vector<vector<int>>result;
        result.push_back(nums);
        while(next_permutation(nums.begin(),nums.end()))
        {
            result.push_back(nums);
        }
        return result;

    }
};

运行结果:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/syyyy712/article/details/81162377