题目

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的更多相关文章

  1. hdu 4739【位运算】.cpp

    题意: 给出n个地雷所在位置,正好能够组成正方形的地雷就可以拿走..为了简化题目,只考虑平行于横轴的正方形.. 问最多可以拿走多少个正方形.. 思路: 先找出可以组成正方形的地雷组合cnt个.. 然后 ...

  2. 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~ ...

  3. 【Valid Sudoku】cpp

    题目: Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could ...

  4. 【Permutations II】cpp

    题目: Given a collection of numbers that might contain duplicates, return all possible unique permutat ...

  5. 【Subsets II】cpp

    题目: Given a collection of integers that might contain duplicates, nums, return all possible subsets. ...

  6. 【Sort Colors】cpp

    题目: Given an array with n objects colored red, white or blue, sort them so that objects of the same ...

  7. 【Sort List】cpp

    题目: Sort a linked list in O(n log n) time using constant space complexity. 代码: /** * Definition for ...

  8. 【Path Sum】cpp

    题目: Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up ...

  9. 【Symmetric Tree】cpp

    题目: Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). F ...

随机推荐

  1. ArcGIS API for Javascript 使用缓冲区结果做query查询出现“esri.config.defaults.io.proxyUrl 尚未进行设置”错误

    1.前言 在研究ArcGIS API for JavaScript时会遇到这样的问题,比如我们在做缓冲区分析时,用分析的范围作为空间查询query的参数,在执行结果中总是会看到“esri.config ...

  2. Java JDBC链接Oracle数据库

    package com.test.test; import java.io.FileInputStream;import java.io.FileNotFoundException;import ja ...

  3. Get query parameter from url

    URL = { getUrlParams: function ( name, url ) { if (!url) url = window.location.href; name = name.rep ...

  4. Sentinel spring-cloud-gateway adapter(1.6)异常错误之@EnableCircuitBreaker

    sentinal 大坑 使用gateway adaper包出现@EnableCircuitBreaker did you forget include starter的异常 这时候千万不要学我引入cl ...

  5. CSS样式中visited,hover,active , focus这四个分别表示什么意思?

    CSS伪类用于向某些选择器添加特殊的效果.CSS又名层叠样式表,所谓层叠,就是后面的样式会覆盖前面的样式,所以在样式表中,各样式排列的顺序很有讲究. :link 与 :visited 在样式文件中的顺 ...

  6. IOS 偏好设置数据 存 取(Preferences文件夹)

    很多iOS应用都支持偏好设置,比如保存用户名.密码.字体大小等设 置,iOS提供了一套标准的解决方案来为应用加入偏好设置功能 每个应用都有个NSUserDefaults实例,通过它来存取偏好设置 比如 ...

  7. 可以让表格变为拖动边界调整列宽度的JS办法

    需要引入文件: jquery.resizableColumns.min.js 和 jquery.resizableColumns.css 代码如下: $(".tableclass" ...

  8. Linux进程的虚拟存储器知识点

    http://blog.csdn.net/yxccc_914/article/details/52665713 用libreoffice画表真时有点蛋疼,效率很低.. 深入理解计算机系统->虚拟 ...

  9. netbackup :nbu备份 Hyper-V 遇到快照错误(状态码 156)

    遇到快照错误(状态码 156) 下表介绍与 NetBackup 状态码 156 有关的 Hyper-V 问题. 表:状态码 156 的可能原因 状态码 156 的原因 说明及推荐操作 NetBacku ...

  10. JavaScript 遍历对象查找指定的值并返回路径

    问:JavaScript 如何查找对象中某个 value 并返回路径上所有的 key? let obj = { key1: 'str1', key2: { key3: 'str3' }, key4: ...