【Next Permutation】cpp
题目:
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 nextPermutation(vector<int> &num) {
const int len = num.size();
if (len<) return;
std::vector<int>::iterator pivot=num.end();
// find the pivot pointer
for (std::vector<int>::iterator i = num.end()-; i != num.begin(); --i)
{
if ( *i>*(i-) )
{
pivot = i-;
break;
}
}
// if the largest, directly reverse
if ( pivot==num.end() )
{
std::reverse(num.begin(), num.end());
return;
}
// else exchange the value of pivot and it's next larger element
std::vector<int>::iterator next_larger_pivot = pivot;
for (std::vector<int>::iterator i = num.end()-; i != num.begin(); --i)
{
if ( *pivot<*i )
{
next_larger_pivot = i;
break;
}
}
std::swap(*pivot, *next_larger_pivot);
// reverse the pivot's right elements
std::reverse(pivot+, num.end());
}
}
Tips:
上网搜搜Next Permutation的算法,分四步:
1. 从右往左 找左比右小的左 记为pivot
2. 从右往左 找第一个比pivot大的 记为next_larger_pivot
3. 交换pivot与next_larger_pivot所指向的元素
4. 让pivot右边的元素(不包括pivot)逆序
按照上面的算法,多测测case,找找边界条件。
注意找到pivot和next_larger_pivot之后要break退出循环。
===================================
第二次过这道题,思路已经记得比较模糊了。能做到的就是捡一遍思路,coding的过程很快。
// from right to left find first violate increase trend
int pos1 = -;
for ( int i=nums.size()-; i>; --i )
{
if ( nums[i]>nums[i-] )
{
pos1 = i-;
break;
}
}
// cout << "pos1:" << pos1 << endl;
if ( pos1==- )
{
std::reverse(nums.begin(), nums.end());
return;
}
// from right to left find the first larger than pos1
int pos2 = nums.size()-;
for ( int i=nums.size()-; i>=; --i )
{
if ( nums[i]>nums[pos1] )
{
pos2 = i;
break;
}
}
// cout << "pos2:" << pos2 << endl;
// swap pos1 pos2
std::swap(nums[pos1], nums[pos2]);
// reverse from pos1's right to end
std::reverse(nums.begin()+pos1+, nums.end());
这个算法就是个套路,多扫几遍记住就OK了。
【Next Permutation】cpp的更多相关文章
- hdu 4739【位运算】.cpp
题意: 给出n个地雷所在位置,正好能够组成正方形的地雷就可以拿走..为了简化题目,只考虑平行于横轴的正方形.. 问最多可以拿走多少个正方形.. 思路: 先找出可以组成正方形的地雷组合cnt个.. 然后 ...
- Hdu 4734 【数位DP】.cpp
题意: 我们定义十进制数x的权值为f(x) = a(n)*2^(n-1)+a(n-1)*2(n-2)+...a(2)*2+a(1)*1,a(i)表示十进制数x中第i位的数字. 题目给出a,b,求出0~ ...
- 【Valid Sudoku】cpp
题目: Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could ...
- 【Permutations II】cpp
题目: Given a collection of numbers that might contain duplicates, return all possible unique permutat ...
- 【Subsets II】cpp
题目: Given a collection of integers that might contain duplicates, nums, return all possible subsets. ...
- 【Sort Colors】cpp
题目: Given an array with n objects colored red, white or blue, sort them so that objects of the same ...
- 【Sort List】cpp
题目: Sort a linked list in O(n log n) time using constant space complexity. 代码: /** * Definition for ...
- 【Path Sum】cpp
题目: Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up ...
- 【Symmetric Tree】cpp
题目: Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). F ...
随机推荐
- java网络编程—TCP(1)
演示tcp的传输的客户端和服务端的互访. 需求:客户端给服务端发送数据,服务端收到后,给客户端反馈信息. 客户端: 1,建立socket服务.指定要连接主机和端口. 2,获取socket流中的输出流. ...
- pta编程题5 Pop Sequence
第一次提交结果都是YES,后来检查发现Push,Pop函数写的有问题,即Stack sta改为引用Stack &sta,否则不能改变实参的值. #include <iostream> ...
- JS事件阻止冒泡的写法
$("body").on("click", "#id", function (ev) { ev = ev || event;要写的逻辑代码 ...
- python 基础之列表切片内置方法
列表操作 c=['cx','zrd','ajt','dne'] #定义一个列表,有4个元素 #增删改查 print(c[3]) #从0计数 测试 D:\python\python.exe D:/unt ...
- js中随机数获取
// 结果为0-1间的一个随机数(包括0,不包括1) var randomNum1 = Math.random(); //console.log(randomNum1); // 函数结果为入参的整数部 ...
- CUDA的软件体系
CUDA的软件堆栈由以下三层构成:CUDA Library.CUDA runtime API.CUDA driver API,如图所示,CUDA的核心是CUDA C语言,它包含对C语言的最小扩展集和一 ...
- Oracle 函数 之 wm_concat()
wm_concat() 把列转换成一行一列显示,使用wm_concat函数可以显示在一行一列. --1 建表 create table province_city ( province varchar ...
- IOS后台执行
大多数应用程序进入后台状态不久后转入暂停状态.在这种状态下,应用程序不执行任何代码,并有可能在任意时候从内存中删除.应用程序提供特定的服务,用户可以请求后台执行时间,以提供这些服务. 判断是否支持多线 ...
- EasyUI获取正在编辑状态行的索引
function getRowIndex(target){ var tr = $(target).closest("tr.datagrid-row"); return paseIn ...
- 4-8 string
1.常用的string模块 import string # 26个小写字母 print(string.ascii_lowercase) # abcdefghijklmnopqrstuvwxyz # 2 ...