class Solution {
public:
void nextPermutation(vector<int>& nums) {
for(int i=nums.size()-2;i>=0;i--)
{
if(nums[i]<nums[i+1])//find the place that the first ascending happens
{
int j;
for(j=nums.size()-1;j>i;j--)//find the number to be swapped with nums[i]
if(nums[j]>nums[i])
break;
swap(nums[i],nums[j]);
reverse(nums.begin()+i+1,nums.end());//make the descending sequence after i becomes ascending
return;
}
}
reverse(nums.begin(),nums.end());
}
};
leetcode 31: Next Permutation
最新推荐文章于 2021-03-10 11:29:57 发布