题目:

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. (Medium)
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

分析:

题意就是找下一个排列,首先可以先复习使用一下STL的next_permutation。

调用next_permutation肯定是能过的。

代码:

 class Solution {
public:
void nextPermutation(vector<int>& nums) {
next_permutation(nums.begin(), nums.begin() + nums.size());
}
};

用next_permutation生成全排列举例如下(参考C++ reference)

 // next_permutation example
#include <iostream> // std::cout
#include <algorithm> // std::next_permutation, std::sort int main () {
int myints[] = {,,}; std::sort (myints,myints+); std::cout << "The 3! possible permutations with 3 elements:\n";
do {
std::cout << myints[] << ' ' << myints[] << ' ' << myints[] << '\n';
} while ( std::next_permutation(myints,myints+) ); std::cout << "After loop: " << myints[] << ' ' << myints[] << ' ' << myints[] << '\n'; return ;
}

所以一般用到next_permutation的题目就是在上面循环的do里面对每次生成的排列做文章。

回头再来看看实现:

这个算法的实现貌似是一个诞生了几百年的经典算法,但是很不好理解其做法的原因,自己梳理一下。

首先要注意的是,我们动一个元素的时候,应该想要改变之后的增值尽可能小。如 124653 -> 125346;

也就是说,高位应该尽量一致,能动低位的时候就不要动高位。如上例子,当4改成5就能增大的时候,不要动1,2。

那4是如何找到的,也就是说最后一个能动的地位是谁呢? 这就应该从后往前看,显然53没得动,653也没得动,但4653可以动了。

原因在于,如果从后往前看的时候,得到的后方元素都是递减的,也就是在这一局部(比如653)他已经没有next_permutation了,所以要再向前找。

只到发现一个位置i, nums[i] < nums[i+1]这意味着 nums[i....size-1] (如4653)这一局部是还有next_permutation。所以位置 i 就是需要被交换。

但他应该交换谁呢?还是考虑上面说的想要改变之后的增值尽可能小,所以应该交互大于nums[i]的最小值,也就是后面位置中从后往前数(从小往大数)第一个大于nums[i]的元素。

当交换完之后,即例子中变为125643,可以发现。nums[i+1,...size-1](即643)一定是完全降序的。

所以为了能组成元素的最小值(这样增值才最小),应该reverse这一部分,变为(346)

得到最终结果125346。

所以综合来讲,算法的流程是(伪代码):

It i = end - ;
while ( (*i > *(i+) )) //找第一个小于后续元素的位置
/* pass */; It j = end;
while ( *j < *i ) //找第一个大于*i的元素
/*pass */ iter_swap(i, j); //交换 *i , *j
reverse(i+, end); // reverse *(i+1)到*end
return true;

代码:

 class Solution {
public:
void nextPermutation(vector<int>& nums) {
if (nums.size() < ) {
return;
}
int i = nums.size() - ;
for (i; i >= ; i--) {
if (nums[i] < nums[i+]) {
break;
}
}
if (i == -) {
sort(nums.begin(), nums.end());
return;
}
int j = nums.size() - ;
for (j; j > i; j--) {
if (nums[j] > nums[i]) {
break;
}
}
swap(nums[i], nums[j]);
reverse(nums.begin() + i + , nums.end()); }
};
 

LeetCode31 Next Permutation的更多相关文章

  1. LeetCode31 Next Permutation and LeetCode60 Permutation Sequence

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

  2. [Swift]LeetCode31. 下一个排列 | Next Permutation

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

  3. Permutation Sequence

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

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

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

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

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

  6. [LeetCode] Permutation Sequence 序列排序

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

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

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

  8. 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 ...

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

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

随机推荐

  1. 【MySql】性能优化之分析命令

    一 当发现程序运行比较慢的时候,首先排除物力资源问题之后,就将注意力转向mysq数据库: 1.首先确定运行慢的sql语句: mysql> show full processlist; 2.确认低 ...

  2. Awk中调用shell命令

    Awk中调用shell命令 需求 在awk中,有时候需要调用linux系统中命令,如计算字符串的MD5值,并保存下来. 方法参考 call a shell command from inside aw ...

  3. spring properties resolve 问题

    在stackoverflow上看到一个问题 配置如下: <context:property-placeholder location="/WEB-INF/application-cus ...

  4. HDU2838Cow Sorting(树状数组)

    题目意思是说给你一列数,每次可以将相邻的两个数交换,这一步的代价是这两个数的和,求将所有数排好序的最少代价. 题解: 我们可以这么思考,由于每次都是交换相邻的两个数,所以将一个数放到它自己的位置去后, ...

  5. HDU 4497 GCD and LCM (数学,质数分解)

    题意:给定G,L,分别是三个数最大公因数和最小公倍数,问你能找出多少对. 析:数学题,当时就想错了,就没找出规律,思路是这样的. 首先G和L有公因数,就是G,所以就可以用L除以G,然后只要找从1-(n ...

  6. hdoj 5399 Tpp simple

    WA了一下午.... 1WA:T了,因为阶乘没打表所以时间超了.. 2WA,3WA:runtime error,检查的value数组开小了,应该是MAXN.. 4WA.5WA.6WA:改了改对cnt的 ...

  7. 网页布局:float与position的区别

    网页开发中布局是一个永恒的话题.巧妙的布局会让网页具有良好的适应性和扩展性.css的布局主要涉及两个属性——position和float.它们俩看上去很容易被弄混,可是仔细分析一下,它们的区别还是很明 ...

  8. linux环境新增用户和所属组

    1.查看用户和组信息命令: 1.1 cat /etc/passwd /etc/passwd 存储有关本地用户的信息. 1)username        UID到名称的一种映射,用户名 2)passw ...

  9. oracle 查詢表字段明細、字段注釋、表註釋

    查詢表字段明細 select  column_name,data_type,data_length,DATA_PRECISION ,DATA_SCALE from all_tab_columns wh ...

  10. arm_cm4.c关于kinetis的修改

    /***********************************************************************/ /* * Initialize the NVIC t ...