runtime 4 ms, beats 94.44% of cpp submissions
O(n x n!) solution with explanation

tags: backtracking

Permutations II

๐Ÿ“– description

็ตฆๅฎšไธ€ๅ€‹้™ฃๅˆ— nums ๏ผŒๅ›žๅ‚ณ่ฉฒ้™ฃๅˆ—ๅ…ƒ็ด ๅฏ็”ข็”Ÿ็š„ๆ‰€ๆœ‰ๆŽ’ๅˆ—็ต„ๅˆๆ–นๅผ๏ผŒๅ…ƒ็ด ๆœ‰ๅฏ่ƒฝ ้‡่ค‡ ๏ผŒๅฏไปฅไปฅไปปไฝ•้ †ๅบๅ›žๅ‚ณ๏ผŒไฝ†ๆ˜ฏ็ต„ๅˆไธ่ƒฝ้‡่ค‡ใ€‚

ex.
    Input: nums = [1,1,2]

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

๐Ÿง  solution

Permutations
solution
ๅฏไปฅๅˆฉ็”จ่ˆ‡ไธŠไธ€้กŒ้กžไผผ็š„ๆžถๆง‹ไพ†ๅฎŒๆˆ๏ผŒไฝ†ๆ˜ฏๅ› ็‚บๅ…ƒ็ด ๆœƒ้‡่ค‡๏ผŒๆ‰€ไปฅ้€™ๆ™‚ๅ€™้œ€่ฆๅฟ…้ ˆไฝฟ็”จ set ไพ†ๅŽป้‡ใ€‚

โณ time complexity

ๅ…ฑๆœ‰ n! ๅ€‹่งฃ (ๆœ€ๅฃž็‹€ๆณไธ‹ๅ…ƒ็ด ๆฒ’ๆœ‰้‡่ค‡)๏ผŒๆฏๅ€‹่งฃ้ƒฝ็ถ“้Ž n ๆฌกไบคๆ›๏ผŒๆ™‚้–“่ค‡้›œๅบฆ O(n x n!)
็ธฝๆ™‚้–“่ค‡้›œๅบฆ O(n x n!)

๐Ÿ“ code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
set<vector<int>> s;
void re(vector<int>& now,int ind){
if(ind==now.size()){
s.insert(now);
}
for(int i=ind;i<now.size();i++){
if(i==ind || (i!=0 && now[i-1]!=now[i])){
swap(now[i],now[ind]);
re(now,ind+1);
swap(now[i],now[ind]);
}
}
}
vector<vector<int>> permuteUnique(vector<int>& nums) {
sort(nums.begin(),nums.end());
re(nums,0);
vector<vector<int>> ans(s.begin(),s.end());
return ans;
}
};