【LeetCode】31. Next Permutation 解题报告(Python & C++)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/problems/next-permutation/description/
题目描述
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 and use only constant 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
题目大意
找到一个排列按照字母表顺序的情况下,下一个更大的排列是多少。如果已经是最大的,那么应该翻转。必须原地翻转。
解题方法
逆序数字交换再翻转
很有技巧的题目。
先找到从后向前数,第一个降序的位置,把此位置后面的翻转。再把这个降序数字和后面第一个比它大的位置交换即可。
首先说一下这题怎么想到的。有如下的一个数组
1 2 7 4 3 1
下一个排列为:
1 3 1 2 4 7
观察可以发现,再给出的数组中,2之后的数字都是降序排列的,我们把2后面第一个比2大的数字放到最前面,然后让3后面的数字升序排列。
简单思路的证明:从7开始是降序的,也就是说7 4 3 1不可能通过重新排列构成更大的数字。如果要得到next permutation,那么必须把2这个位置的数字给换掉才行,而且只能换成比2大的数字在才能使next permutation > current permutation.至于换成多大的数字,很明显的需要换成在2后面的数字中刚好比2大的数字,证明可以使用反证法来说明换成其他数字要么比当前数字小,要么大于正确的next permutation.
下面这个做法是先逆序再交换,本质和上面的证明一样:
如果从第n个数字到最后都是递减的并且第n-1个数字小于第n个,说明从第n个数字开始的这段序列是字典序组合的最后一个,在下一个组合中他们要倒序变为字典序第一个,然后从这段序列中找出第一个大于第n-1个数字的数和第n-1个数字交换就可以了。
举个栗子,当前组合为12431,可以看出431是递减的,同时4>2,这样我们把431倒序,组合就变为12134,然后从134中找出第一个大于2的数字和2交换,这样就得到了下一个组合13124。对于完全递减的组合例如4321在倒序之后就可以结束了。
代码如下:
class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
n = len(nums)
i = n - 1
while i > 0 and nums[i] <= nums[i - 1]:
i -= 1
self.reverse(nums, i, n - 1)
if i > 0:
for j in range(i, n):
if nums[j] > nums[i-1]:
self.swap(nums, i-1, j)
break
def reverse(self, nums, i, j):
"""
contains i and j.
"""
for k in range(i, (i + j) / 2 + 1):
self.swap(nums, k, i + j - k)
def swap(self, nums, i, j):
"""
contains i and j.
"""
nums[i], nums[j] = nums[j], nums[i]
也可以先进行交换,然后再翻转。比如Leetcode的这个解答方式:

C++代码如下:
class Solution {
public:
void nextPermutation(vector<int>& nums) {
const int N = nums.size();
int i = N - 2;
while (i >= 0 && nums[i] >= nums[i + 1]) --i;
int j = N - 1;
if (i >= 0) {
while (nums[j] <= nums[i]) --j;
swap(nums[i], nums[j]);
}
reverse(nums.begin() + i + 1, nums.end());
}
};
库函数
这个算我第一次觉得C++让人惊呆吧,有next_permutation函数,而且是原地操作。
class Solution {
public:
void nextPermutation(vector<int>& nums) {
next_permutation(nums.begin(), nums.end());
}
};
参考资料:
- https://leetcode.com/articles/next-permutation/
- https://blog.csdn.net/tstsugeg/article/details/50261517
- http://www.cnblogs.com/grandyang/p/4428207.html
日期
2018 年 8 月 27 日 ———— 就要开学了!
2019 年 1 月 14 日 —— 凛冬将至
【LeetCode】31. Next Permutation 解题报告(Python & C++)的更多相关文章
- 【LeetCode】784. Letter Case Permutation 解题报告 (Python&C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 回溯法 循环 日期 题目地址:https://leet ...
- 【LeetCode】Permutations II 解题报告
[题目] Given a collection of numbers that might contain duplicates, return all possible unique permuta ...
- 【LeetCode】120. Triangle 解题报告(Python)
[LeetCode]120. Triangle 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址htt ...
- 【LeetCode】Gas Station 解题报告
[LeetCode]Gas Station 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/gas-station/#/descr ...
- LeetCode 1 Two Sum 解题报告
LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...
- [array] leetcode - 31. Next Permutation - Medium
leetcode - 31. Next Permutation - Medium descrition Implement next permutation, which rearranges num ...
- LeetCode 31 Next Permutation / 60 Permutation Sequence [Permutation]
LeetCode 31 Next Permutation / 60 Permutation Sequence [Permutation] <c++> LeetCode 31 Next Pe ...
- 【LeetCode】Island Perimeter 解题报告
[LeetCode]Island Perimeter 解题报告 [LeetCode] https://leetcode.com/problems/island-perimeter/ Total Acc ...
- 【LeetCode】01 Matrix 解题报告
[LeetCode]01 Matrix 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/01-matrix/#/descripti ...
随机推荐
- DNS域名解析全过程
一张图看懂DNS域名解析全过程 DNS域名解析是互联网上非常重要的一项服务,上网冲浪(还有人在用这个词吗?)伴随着大量DNS服务来支撑,而对于网站运营来说,DNS域名解析的稳定可靠,意味着更多用户 ...
- sersync+rsync进行数据同步
一:环境 操作系统环境:redhat6.6 内核版本:2.6.32-358.el6.x86_64 rsync server:192.168.2.3(部署rsync server) rsync clie ...
- 50. Plus One-Leetcode
Plus One My Submissions QuestionEditorial Solution Total Accepted: 98403 Total Submissions: 292594 D ...
- adjust, administer
adjust to just, exact. In measurement technology and metrology [度量衡学], calibration [校准] is the compa ...
- accommodate ~ ache
accommodate The accommodation reflex [反射] (or accommodation-convergence [会聚] reflex) is a reflex act ...
- 如何从 100 亿 URL 中找出相同的 URL?
题目描述 给定 a.b 两个文件,各存放 50 亿个 URL,每个 URL 各占 64B,内存限制是 4G.请找出 a.b 两个文件共同的 URL. 解答思路 每个 URL 占 64B,那么 50 亿 ...
- 深入理解java动态代理机制
动态代理其实就是java.lang.reflect.Proxy类动态的根据您指定的所有接口生成一个class byte,该class会继承Proxy类,并实现所有你指定的接口(您在参数中传入的接口数组 ...
- Dubbo服务分组
服务分组与多版本控制的使用方式几乎是相同的,只要将version替换为group即可.但使用目的不同.使用版本控制的目的是为了升级,将原有老版本替换掉,将来不再提供老版本的服务,所以不同版本间不能出现 ...
- 一个统计 CPU 内存 硬盘 使用率的shell脚本
一个统计 CPU 内存 硬盘 使用率的shell脚本,供大家学习参考 #!/bin/bash #This script is use for describle CPU Hard Memery Uti ...
- my40_MySQL锁概述之意向锁
本文在锁概述的基础上,通常实验举例,详细地介绍了意向锁的原理. 锁范围 全局锁(global lock)表锁(table lock)行锁 (row lock) ROW LOCK的粒度LOCK_REC ...