LeetCode - 47. Permutations II

简介: 47. Permutations II  Problem's Link  ---------------------------------------------------------------------------- Mean:  给定一个数组(元素可能重复),求这个数组的全排列.

47. Permutations II 

Problem's Link

 ----------------------------------------------------------------------------

Mean: 

给定一个数组(元素可能重复),求这个数组的全排列.

analyse:

注意需要先排序,和上一题的区别在于当发现要交换的两数相等时,无需再往下递归,避免了重复的排列.

Time complexity: O(N)

 

view code

#include <bits/stdc++.h>
using namespace std;

class Solution
{
public :
    vector < vector < int >> permuteUnique( vector < int > nums)
    {
        sort( nums . begin (), nums . end());
        vector < vector < int >> res;
        permutate( res , nums , 0);
        return res;
    }

    void permutate( vector < vector < int >>& res , vector < int > nums , int begin)
    {
        if( begin >= nums . size())
            res . push_back( nums);
        for( int i = begin; i < nums . size(); ++ i)
        {
            if( i != begin && nums [ i ] == nums [ begin ])
                continue;
            swap( nums [ i ], nums [ begin ]);
            permutate( res , nums , begin + 1);
        }
    }
};

int main()
{
    int n;
    while( cin >>n)
    {
        vector < int > nums(n);
        for( int i = 0; i <n; ++ i)
            cin >> nums [ i ];
        Solution solution;
        auto ans = solution . permuteUnique( nums);
        for( auto p1: ans)
        {
            for( auto p2: p1)
            {
                cout << p2 << " ";
            }
            cout << endl;
        }
    }
    return 0;
}
目录
相关文章
|
人工智能
LeetCode 47. Permutations II
给定一组可能有重复元素不同的整数,返回所有可能的排列(不能包含重复)。
53 0
LeetCode 47. Permutations II
LeetCode 46. Permutations
给定一组不同的整数,返回所有可能的排列。
37 0
|
算法
[LeetCode]--47. Permutations II
Given a collection of numbers that might contain duplicates, return all possible unique permutations. For example, [1,1,2] have the following unique permutations: [ [1,1,2], [1,2,1],
1033 0
[LeetCode]--46. Permutations
Given a collection of distinct 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],
1218 0
LeetCode - 46. Permutations
46. Permutations  Problem's Link  ---------------------------------------------------------------------------- Mean:  给定一个数组,求这个数组的全排列.
875 0
[LeetCode] Permutations
Well, have you solved the nextPermutation problem? If so, your code can be used in this problem. The idea is fairly simple: sort nums in ascending o...
874 0
[LeetCode] Permutations II
Well, have you solved the nextPermutation problem? If so and you have handled the cases of duplicates at that problem, your code can be used in this problem.
678 0