LeetCode-31. 下一个排列(Next Permutation)

STL or Manual

  1. STL
class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        next_permutation(nums.begin(), nums.end());
    }
};
  1. Manual
class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int i = nums.size() - 2;
        while(0 <= i && nums[i + 1] <= nums[i]){
        	i--;
        }
        if(i >= 0){
        	int j = nums.size() - 1;
        	while(0 <= j && nums[j] <= nums[i]){
        		j--;
        	}
        	swap(nums, i, j);
        }
        reverse(nums, i + 1);
    }
    void reverse(vector<int>& nums,int i){
    	int j = nums.size() - 1;
    	while(i < j) {
    		swap(nums, i, j);
    		i++;
    		j--;
    	}
    }
    void swap(vector<int>& nums,int i,int j){
    	int temp = nums[i];
    	nums[i] = nums[j];
    	nums[j] = temp;
    }
};

题目链接:https://leetcode-cn.com/problems/next-permutation/

发布了42 篇原创文章 · 获赞 2 · 访问量 1402

猜你喜欢

转载自blog.csdn.net/Listen_heart/article/details/103187620