Skip to content

Commit 7a5bac3

Browse files
🔢 Day 12
1 parent c794052 commit 7a5bac3

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
2. [Maximum Difference Between Node and Ancestor](https://leetcode.com/explore/challenge/card/november-leetcoding-challenge/565/week-2-november-8th-november-14th/3525/) ➡️ [CPP Solution](Week2/maxAncestorDiff.cpp)
1919
3. [Flipping an Image](https://leetcode.com/explore/challenge/card/november-leetcoding-challenge/565/week-2-november-8th-november-14th/3526/) ➡️ [CPP Solution](Week2/flipAndInvertImage.cpp)
2020
4. [Valid Square](https://leetcode.com/explore/challenge/card/november-leetcoding-challenge/565/week-2-november-8th-november-14th/3527/) ➡️ [CPP Solution](Week2/validSquare.cpp)
21+
5. [Permutations II](https://leetcode.com/explore/challenge/card/november-leetcoding-challenge/565/week-2-november-8th-november-14th/3528/) ➡️ [CPP Solution](Week2/permuteUnique.cpp)
2122

2223
## Week 3 🚧
2324
Coming soon...

Week2/permuteUnique.cpp

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// Approach 1 - Set
2+
class Solution {
3+
private:
4+
void permute(set<vector<int>>& s, vector<int>& nums, int start) {
5+
if(start == nums.size()) {
6+
s.insert(nums);
7+
} else {
8+
for(int i = start; i < nums.size(); ++i) {
9+
swap(nums[i], nums[start]);
10+
permute(s, nums, start + 1);
11+
swap(nums[i], nums[start]);
12+
}
13+
}
14+
}
15+
public:
16+
vector<vector<int>> permuteUnique(vector<int>& nums) {
17+
set<vector<int>> s;
18+
permute(s, nums, 0);
19+
20+
vector<vector<int>> result(s.begin(), s.end());
21+
return result;
22+
}
23+
};
24+
25+
// Approach Two - Map to avoid unnecessary calls
26+
class Solution {
27+
private:
28+
void permute(map<int, int>& m, vector<vector<int>>& result, vector<int>& temp, int start) {
29+
if(start == temp.size()) {
30+
result.push_back(vector<int>(temp.begin(), temp.end()));
31+
} else {
32+
for(auto &x: m) {
33+
if(x.second > 0) {
34+
m[x.first] = x.second - 1;
35+
temp[start] = x.first;
36+
permute(m, result, temp, start + 1);
37+
m[x.first] = x.second + 1;
38+
}
39+
}
40+
}
41+
}
42+
public:
43+
vector<vector<int>> permuteUnique(vector<int>& nums) {
44+
vector<vector<int>> result;
45+
map<int, int> m;
46+
vector<int> temp(nums.size());
47+
48+
for(int num: nums)
49+
m[num]++;
50+
51+
permute(m, result, temp, 0);
52+
return result;
53+
}
54+
};

0 commit comments

Comments
 (0)