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

  

class Solution {
public:
void reverse(int begin, int end , vector<int> &num)
{
assert(begin >= && begin <= end && end < num.size()); int i = begin , j = end;
while(i<j)
{
int temp = num[i];
num[i] = num[j];
num[j] = temp;
i++;
j--;
}
}
void nextPermutation(vector<int> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int len = num.size();
if(len < ) return ;
int i, j;
for( i = len - ; i>= ; i-- )
if(num[i] >= num[i+])
continue;
else
break; if(i>=)
{
j = len -;
while(j >= && num[j] <= num[i])j--; int temp = num[i];
num[i] = num[j];
num[j] = temp;
}
reverse(i+, len-, num);
}
};

reference :

http://stackoverflow.com/questions/11483060/stdnext-permutation-implementation-explanation

http://yucoding.blogspot.com/2013/04/leetcode-question-61-next-permutation.html

http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html

一个很好的解释,来字stackoverflow

Let's look at some permutations:

...
How do we go from one permutation to the next? Firstly, let's look at things a little differently. We can view the elements as digits and the permutations as numbers. Viewing the problem in this way we want to order the permutations/numbers in "ascending" order. When we order numbers we want to "increase them by the smallest amount". For example when counting we don't count 1, 2, 3, 10, ... because there are still 4, 5, ... in between and although 10 is larger that 3, there are missing numbers which can be gotten by increasing 3 by a smaller amount. In the example above we see that 1 stays as the first number for a long time as there are many reorderings of the last 3 "digits" which "increase" the permutation by a smaller amount. So when do we finally "use" the ? When there are only no more permutations of the last digits.
And when are there no more permutations of the last digits? When the last digits are in descending order. Aha! This is key to understanding the algorithm. We only change the position of a "digit" when everything to the right is in descending order because if it isn't in descending order then there are still more permutations to go (ie we can "increase" the permutation by a smaller amount). Let's now go back to the code: while (true)
{
It j = i;
--i; if (*i < *j)
{ // ...
} if (i == begin)
{ // ...
}
}
From the first lines in the loop j is an element and i is the element before it.
Then if the elements are in ascending order (if (*i < *j)) do something.
Otherwise if the whole thing is in descending order (if (i == begin)) then this is the last permutation.
Otherwise we continue and we see that j and i are essentially decremented. We now understand the if (i == begin) part so all we need to understand is the if (*i < *j) part. Also note: "Then if the elements are in ascending order ..." which supports out previous observation that we only need to do something to a digit "when everything to the right is in descending order". The ascending order if statement is essentially finding the leftmost place where "everything to the right is in descending order". Let's look again at some examples: ... ... ...
We see that when everything to the right of a digit is in descending order, we find the next largest digit and put it in front and then put the remaining digits in ascending order. Let's look at the code: It k = end; while (!(*i < *--k))
/* pass */; iter_swap(i, k);
reverse(j, end);
return true;
Well since the things to the right are in descending order, to find the "next largest digit" we just have to iterate from the end which we see in the first lines of code. Next we swap the "next largest digit" to the front with the iter_swap() statement and then since we know that that digit was the next largest, we know that the digits to the right are still in descending order so to put it in ascending order we just have to reverse() it.

LeetCode_Next Permutation的更多相关文章

  1. Permutation Sequence

    The set [1,2,3,-,n] contains a total of n! unique permutations. By listing and labeling all of the p ...

  2. [LeetCode] Palindrome Permutation II 回文全排列之二

    Given a string s, return all the palindromic permutations (without duplicates) of it. Return an empt ...

  3. [LeetCode] Palindrome Permutation 回文全排列

    Given a string, determine if a permutation of the string could form a palindrome. For example," ...

  4. [LeetCode] Permutation Sequence 序列排序

    The set [1,2,3,…,n] contains a total of n! unique permutations. By listing and labeling all of the p ...

  5. [LeetCode] Next Permutation 下一个排列

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

  6. Leetcode 60. Permutation Sequence

    The set [1,2,3,-,n] contains a total of n! unique permutations. By listing and labeling all of the p ...

  7. UVA11525 Permutation[康托展开 树状数组求第k小值]

    UVA - 11525 Permutation 题意:输出1~n的所有排列,字典序大小第∑k1Si∗(K−i)!个 学了好多知识 1.康托展开 X=a[n]*(n-1)!+a[n-1]*(n-2)!+ ...

  8. Permutation test: p, CI, CI of P 置换检验相关统计量的计算

    For research purpose, I've read a lot materials on permutation test issue. Here is a summary. Should ...

  9. Permutation

    (M) Permutations (M) Permutations II (M) Permutation Sequence (M) Palindrome Permutation II

随机推荐

  1. Keil 3光标问题 以及汉字问题

    初次使用keil3,光标总是定位不准,修改十分麻烦,google后解决问题,修改tools.ini如下(蓝色为加入项): NAME="YGLenovo User", "a ...

  2. HTTP methods 与 RESTful API

    Note GET, primarily used to select resources. Other options for an API method include: POST, primari ...

  3. BZOJ1532: [POI2005]Kos-Dicing

    1532: [POI2005]Kos-Dicing Time Limit: 5 Sec  Memory Limit: 64 MBSubmit: 1060  Solved: 321[Submit][St ...

  4. Linux企业级项目实践之网络爬虫(7)——DNS解析

    DNS 是Domain Name Service的缩写.域名系统为Internet上的主机分配域名地址和IP地址.IP地址不易于记忆,然而域名地址相比较而言是方便于记忆的.用户如果使用域名地址,当想获 ...

  5. hdu1573:数论,线性同余方程组

    题目大意: 给定一个N ,m 找到小于N的  对于i=1....m,满足  x mod ai=bi  的 x 的数量. 分析 先求出 同余方程组 的最小解x0,然后 每增加lcm(a1...,am)都 ...

  6. jQuery鼠标悬停图片放大显示

    jQuery鼠标悬浮放于图片上之后图片放大显示的效果,即鼠标移到图片上图片突出显示,鼠标移开后恢复原来的模样,你可以在图片滚动效果中加上本特效,相信会更炫一些. <!DOCTYPE html P ...

  7. Hive2.0函数大全(中文版)

    摘要 Hive内部提供了很多函数给开发者使用,包括数学函数,类型转换函数,条件函数,字符函数,聚合函数,表生成函数等等,这些函数都统称为内置函数. 目录 数学函数 集合函数 类型转换函数 日期函数 条 ...

  8. STM32F051 IAP源代码分享

    STM32F051 IAP源代码分享 假设不懂IAP的请自己主动脑补或者怒戳这里 http://www.openedv.com/posts/list/11494.htm 然后STM32F051的IAP ...

  9. JMeter简单性能测试(适合初学者)

    利用JMeter进行Web测试     JMeter介绍    脚本录制    运行JMeter进行测试    JMeter主要组件介绍    参数化设置    动态数据关联    使用命令行运行JM ...

  10. BNU10805:矩形神码的

    我们都知道,矩形是由两条对角线的,没错吧?(谜之声:这不是显然么!)这两条线的长度也是相等的,没错吧?(谜之声:这不废话么!)然后我们给定一条对角线的起始点和终止点的坐标,然后给定另一个对角线和他的夹 ...