您的位置:首页 > 其它

leetcode题集——next-permutation

2016-07-19 17:35 197 查看
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

字典序排列。理解题意万岁!!!

大致分为三个步骤:

假设vector<int> num有len个元素,

STEP 1:从右(len-1)向左(i)遍历,找到num[i]>num[i-1]。如果没有,则i==0,将num从小到大排序,作为返回值。

STEP 2:同样地,从右(len-1)向左(i)遍历,找到从最右边开始,第一个比num[i-1]大的元素下标minindex。并交换num[i-1]与num[minindex]。

STEP 3:将新的num[i]到num[len-1]从小到大排序。

class Solution {
public:
void swap(int &a,int &b)
{
int tem=a;
a=b;
b=tem;
}
void nextPermutation(vector<int> &num)
{
int len=num.size();

int i;
for(i=len-1;i>0;i--)
{
if(num[i-1]<num[i])
break;
}
//当排列的所有元素递减时,表示最大值。返回最小值
if(i==0)
{
std::sort(num.begin(),num.end());
return;
}

int minindex=i;
for(int j=len-1;j>=i;j--)
{
if(num[j]>num[i-1])
{
minindex=j;
break;
}
}
swap(num[i-1],num[minindex]);
std::sort(num.begin()+i,num.end());
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: