Skip to content

Commit 62db505

Browse files
authored
Added C++ solution
31. Next Permutation C++ solution
1 parent b94b4ad commit 62db505

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

cpp/_31.cpp

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution {
2+
public:
3+
void nextPermutation(vector<int>& nums) {
4+
5+
int i1,i2;
6+
bool hasPermutation = false;
7+
for(int i=nums.size()-1;i>0;i--){
8+
if(nums[i-1]<nums[i]){
9+
i1 = i-1;
10+
i2 = i;
11+
hasPermutation = true;
12+
break;
13+
}
14+
}
15+
16+
if(hasPermutation){
17+
int j=i2;
18+
for(int i=nums.size()-1;i>i1;i--){
19+
if(nums[i]>nums[i1]){
20+
j=i;
21+
break;
22+
}
23+
}
24+
swap(nums[i1],nums[j]);
25+
reverse(nums.begin()+i1+1,nums.end());
26+
}else{
27+
sort(nums.begin(),nums.end());
28+
}
29+
for(auto i:nums){
30+
cout << i << " ";
31+
}
32+
}
33+
};

0 commit comments

Comments
 (0)