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怎么像makefile那样选择哪些文件进行编译?

    因为设备有多种不同的型号的硬件,所以就有不同的驱动,我想在编译的时候,像在linux下的makeile那样,自己写一个编译连接的东西,来控制我哪些文件进行编译链接,不知道在keil下有没有这样的方法. ...

  2. 【剑指offer】面试题42:翻转单词顺序 VS 左旋转字符串

    题目: 汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果.对于一个给定的字符序列S,请你把其循环左移K位后的序列输出.例如,字符序列S=”abcX ...

  3. 【HDU】I love sneakers!(分组背包)

    看了许多的题解,都有题目翻译,很不错,以后我也这样写.直接翻译样例: /*鞋子的数量N[1, 100]; 拥有的金钱M[1, 1w]; 品牌数目[1, 10]*/ /*以下四行是对于每双鞋的描述*/ ...

  4. Struts分页

    1.分页的bean类PaginationSupport.java  2.写好后直接在action里面调用,计算当前页显示的数据  3.写一个公用的jsp页面,直接在需要分页的页面include就可以了 ...

  5. Appium 一个测试套件多次启动android应用

    AppiumDriver<WebElement> driver; File classpathRoot = new File(System.getProperty("user.d ...

  6. class 类(1)

    创建类 #!/usr/bin/env python # coding=utf-8 __metaclass__ = type class Person: def __init__(self, name) ...

  7. jQuery插件开发 格式与解析

    jQuery插件的开发包括两种: 一种是类级别的插件开发,即给jQuery添加新的全局函数,相当于给jQuery类本身添加方法.jQuery的全局函数就是属于jQuery命名空间的函数,另一种是对象级 ...

  8. cp命令的编写——浅谈系统调用

    摘要:linux中cp命令的实现,通过这个程序,我们需要了解系统调用耗费时间的方面,同时学会系统调用的错误处理机制. 本文来源:http://blog.csdn.net/trochiluses/art ...

  9. 视图中的Layout使用(转)

    1.母板页_Layout.cshtml 类似于传统WebForm中的.master文件,起到页面整体框架重用的目地 1.母板页代码预览 1 <!DOCTYPE html> 2 <ht ...

  10. Java数据结构漫谈-ArrayList

    ArrayList是一个基于数组实现的链表(List),这一点可以从源码中看出: transient Object[] elementData; // non-private to simplify ...