Skip to content

Commit 4aed337

Browse files
committed
3
1 parent 5dc95bf commit 4aed337

File tree

1 file changed

+20
-29
lines changed

1 file changed

+20
-29
lines changed

PermutationsII/PermutationsII.cpp

+20-29
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,31 @@
11
class Solution {
22
public:
3-
vector<vector<int>> permuteUnique(vector<int>& num) {
4-
// Start typing your C/C++ solution below
5-
// DO NOT write int main() function
6-
3+
vector<vector<int> > permuteUnique(vector<int> &num) {
74
vector<vector<int>> result;
8-
5+
sort(num.begin(), num.end());
96
do {
107
result.push_back(num);
11-
nextPermutation(num);
12-
} while (!isEqual(result[0], num));
13-
14-
return move(result);
8+
} while (getNext(num));
9+
return result;
1510
}
1611

17-
bool isEqual(vector<int>& n1, vector<int>& n2) {
18-
if (n1.size() != n2.size())
12+
bool getNext(vector<int>& num) {
13+
int i = num.size() - 1;
14+
while (i >= 1 && num[i-1] >= num[i]) {
15+
i--;
16+
}
17+
if (i == 0) {
1918
return false;
20-
for (int i = 0; i < n1.size(); i++) {
21-
if (n1[i] != n2[i]) return false;
2219
}
23-
return true;
24-
}
25-
26-
void nextPermutation(vector<int>& num) {
27-
int lf = num.size() - 2;
28-
while (lf >= 0 && num[lf] >= num[lf+1])
29-
lf -= 1;
30-
if (lf == -1) {
31-
reverse(num.begin(), num.end());
32-
return;
20+
int j = num.size() - 1;
21+
while (j >= i) {
22+
if (num[j] > num[i-1]) {
23+
break;
24+
}
25+
j--;
3326
}
34-
int rt = num.size() - 1;
35-
while (rt > lf && num[rt] <= num[lf])
36-
rt -= 1;
37-
swap(num[lf], num[rt]);
38-
reverse(num.begin() + lf + 1, num.end());
27+
swap(num[i-1], num[j]);
28+
reverse(num.begin() + i, num.end());
29+
return true;
3930
}
40-
};
31+
};

0 commit comments

Comments
 (0)