Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6f67f4c

Browse files
mathmatics solution & speed up
1 parent 989e33e commit 6f67f4c

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
class Solution {
2+
private:
3+
void my_next_permutation(vector<int>::iterator b, vector<int>::iterator e)
4+
{
5+
// 指针从后往前移动找到第一个下降值, (如 1, 3, 2 的1为下降值)
6+
// 在这个下降值(1)后面找一个比下降值大的最小值(2),与下降值(1)交换
7+
// 交换后原来下降值之后的位置做排序(2, 1, 3)
8+
vector<int>::iterator p = e-2 ;
9+
while (p >= b && *p >= *(p+1))
10+
--p ;
11+
12+
if (p >= b)
13+
{
14+
int M = *p ;
15+
vector<int>::iterator pnindex = p ;
16+
for (vector<int>::iterator pn = p+1 ; pn < e; ++pn)
17+
if (*pn > *p)
18+
{
19+
M = min(M, *pn) ;
20+
pnindex = pn ;
21+
}
22+
swap(*p, *pnindex) ;
23+
sort(p+1, e) ;
24+
}
25+
else
26+
sort(b, e) ;
27+
}
28+
inline bool IsSample(vector<int> &a, vector<int> &b)
29+
{
30+
// 长度肯定一样,就不用比较长度了
31+
for (int i = a.size()-1; i >= 0; --i)
32+
if (a[i] != b[i])
33+
return false ;
34+
return true ;
35+
}
36+
public:
37+
vector<vector<int>> permuteUnique(vector<int>& nums) {
38+
vector<int> nums_bak(nums) ;
39+
vector<vector<int>> res ;
40+
41+
do
42+
{
43+
res.push_back(nums) ;
44+
my_next_permutation(nums.begin(), nums.end()) ;
45+
} while ( !IsSample(nums, nums_bak) ) ;
46+
47+
return res ;
48+
}
49+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /