Leetcode 47 Permutations II

2018-01-12 15:06:54 浏览数 (4)

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

For example, [1,1,2] have the following unique permutations:

代码语言:javascript复制
[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]

和46题差不多,区别是有重复元素,加一个sort,判断重复元素就行了。

实在不想在DFS了,偷个懒!

代码语言:javascript复制
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_permutation(nums.begin(),nums.end()));  
        return result;  
    }
};

1 人点赞