1. 程式人生 > >Leetcode 46. Permutations 和Leetcode 47. Permutations II

Leetcode 46. Permutations 和Leetcode 47. Permutations II

本文中這兩題全排列的解法採用了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;

    }
};

執行結果:
這裡寫圖片描述