【Leetcode】之Next Permutation

来源:互联网 发布:2016知乎日报启动画面 编辑:程序博客网 时间:2024/05/14 09:37

一.问题描述

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place, do not allocate extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

二.我的解题思路

首先要理解什么叫字典序排列,可参见博客:http://blog.csdn.net/zhutulang/article/details/7763810。
弄清楚什么叫字典序排列之后,这套题目就转换成了常见的数组问题,测试通过的程序如下:

class Solution {public:    void nextPermutation(vector<int>& nums) {        int len=nums.size();        bool flag=0;int r=0;        //从数组的右侧开始寻找第一个nums[r-1]<nums[r]的数        for( r=len-1;r>0;r--){               if(nums[r-1]<nums[r]){                flag=1; break;            }        }        //需要按从小到大的顺序进行排列        if(flag==0){            reverse(nums,0,len-1);        }        else{            int curr_idx= r-1;            int min=nums[curr_idx+1];int min_idx=curr_idx+1;            for(int r=curr_idx+1;r<len;r++){                   if(nums[r]>nums[curr_idx]){                    if(nums[r]<=min){                        min=nums[r];min_idx=r;                                    }                                   }            }            swap(nums[curr_idx],nums[min_idx]);            reverse(nums,curr_idx+1,len-1);    }    }private:      void swap(int& a,int& b){        int tmp=0;        tmp=b;        b=a;        a=tmp;    }    void reverse(vector<int>& nums,int st,int end){        int tmp=0;        while(st<=end){            tmp=nums[st];            nums[st]=nums[end];            nums[end]=tmp;            st++;            end--;        }    }};
0 0
原创粉丝点击