Leetcode 31 Next Permutation (C++实现)
来源:互联网 发布:千锋 育知同创 编辑:程序博客网 时间:2024/05/31 11:03
题目:
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
这个题目最无语的地方在于一般人看不懂题目要求说的是什么。尤其是lexicographically这个关键词让人一脸懵逼。题目的意思就是,还是这几个数字,找出比当前排列大的排列中最小的那一个。
奥斯卡的叫法经过在草稿纸上演算了几种情况之后,得到下面可以想到的不需要分类讨论的通法(唯一一个需要注意的就是是否没有比当前大的排列了——序列中的数字是降序,这时应该返回最小的排列——所有数字的升序序列。)
算法:
1. 从所给序列nums的尾部开始向前搜索,搜索过的序列记为S,直到发现下降的相邻数字,或者搜索到序列首。
2. if 没有搜索到序列首:
a = S前面的数字
b = S中比a大的最小的数字
交换a和b
3. 对S进行升序(非降序)排序
#include <iostream>#include <vector>using namespace std;// We can define another function swap() to make the codes clearer. reverse(), too.class Solution {public: void nextPermutation(vector<int>& nums) { int temp = -1; int i; int len = nums.size(); vector<int> seq; for(i = len - 1; i >= 0; i--) { if (nums[i] >= temp) { temp = nums[i]; seq.push_back(temp); // the numbers in seq vector is in forward order. } else break; } if (i != -1) { int t = nums[i]; for (int j = 0; j < seq.size(); j++) { if (seq[j] > t) { nums[i] = nums[len-1-j]; nums[len-1-j] = t; break; } } } for (int j = 0; j < (len-1-i)/2; j++) { int t = nums[i+1+j]; nums[i+1+j] = nums[len-1-j]; nums[len-1-j] = t; } }};int main() { Solution s; vector<int> nums; nums.push_back(1); nums.push_back(2); nums.push_back(3); // 测试123的所有排序是否按序输出 for(int i = 0; i < 6; i++) { s.nextPermutation(nums); for (int j = 0; j < nums.size(); j++) { cout << nums[j] << " "; } cout << endl; } return 0;}
- [leetcode-31]Next Permutation(C)
- Leetcode 31 Next Permutation (C++实现)
- LeetCode(31): Next Permutation (C++)
- LeetCode(31) Next Permutation
- LeetCode (31)Next Permutation
- 【LeetCode算法练习(C++)】Next Permutation
- LeetCode 31: Next Permutation
- [leetcode 31] Next Permutation
- LeetCode(31) Next Permutation
- LeetCode---(31) Next Permutation
- leetcode 31 -- Next Permutation
- leetcode 31: Next Permutation
- LeetCode(31) Next Permutation
- LeetCode-31 Next Permutation
- Leetcode#31||Next Permutation
- LeetCode 31: Next Permutation
- LeetCode(31)-Next Permutation
- leetcode(31) Next Permutation
- javaweb---常见错误(一)
- Microsoft Windows 平台下 API调用与单片机进行串口通信
- ubuntu14.04+caffe+opencv
- crontab 任务调度
- vue2-计算属性
- Leetcode 31 Next Permutation (C++实现)
- ZooKeeper源码解析(二):用户如何和ZooKeeper交互
- 线程安全和可重入函数的关系,区别
- opencv之canny边缘检测
- BZOJ 3489 A simple rmq problem
- 实现如下页面布局。核心区域左侧自适应,右侧固定宽度 200px
- Glide超全详解
- 利用割线法求解一元函数极小值
- 详解4字节对齐