【LeetCode】97. Permutations II

题目描述(Medium)

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

题目链接

https://leetcode.com/problems/permutations-ii/description/

Example 1:

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

算法分析

自己实现next_permutation(),详见【LeetCode】12.Next Permutation,时间复杂度O(n!),空间复杂度O(1)

提交代码:

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

    bool next_permutations(vector<int>& nums)
    {
        auto rfirst = nums.rbegin();
        auto rlast = nums.rend();
        
        auto pivot = rfirst + 1;
        while (pivot != rlast && *pivot >= *(pivot - 1))
            ++pivot;
        
        if (pivot == rlast)
            return false;
        
        auto onchange = find_if(rfirst, pivot, bind1st(less<int>(), *pivot));
        
        swap(*pivot, *onchange);
        reverse(rfirst, pivot);
        return true;
    }
};

猜你喜欢

转载自blog.csdn.net/ansizhong9191/article/details/83025502