常见算法问题之NextPermutation
来源:互联网 发布:javascript与html论文 编辑:程序博客网 时间:2024/06/06 21:38
题目来源于leetcode 31
1. 问题描述
依据字典序升序,找出序列的下一序列。例如(左边是输入,右边是输出):
1 2 3 --- 1 3 21 5 1 --- 5 1 13 2 1 --- 1 2 3
2. 算法描述
for (i = 0; i < size(array); i++) j = max{i | array[i] < array[i + 1]};for (i = 0; i < size(array); i++) k = max{i | array[i] > array[j]};swap(j, k);reverse(array, j+1, array(end));
3. C++实现
#include <iostream>#include <vector>using namespace std;class Solution {public: void nextPermutation(vector<int>& nums) { vector<int>::iterator i, j, k, reverse_start = nums.begin(); bool is_found = 0; //若原序列恰好是降序,则reverse范围是整个序列 for (i = nums.begin(), j = i; i != nums.end() - 1; i++) { if (*i < *(i + 1)) { j = i; is_found = 1; } } if (is_found != 0) { for (i = nums.begin(); i != nums.end(); i++) { if (*j < *i) k = i; } reverse_start = j + 1; swap(j, k); } reverse(nums, reverse_start); }private: void reverse(vector<int>& nums, vector<int>::iterator start) { vector<int>::iterator i = start; vector<int>::iterator j = nums.end() - 1; while (i < j) { swap(i, j); i++; j--; } } void swap(vector<int>::iterator i, vector<int>::iterator j) { int temp = *i; *i = *j; *j = temp; }};int main(){ const int n = 3; int b[n] = {3, 2, 1}; vector<int> a(b, b + n); Solution S; S.nextPermutation(a); vector<int>::iterator iter; for (iter = a.begin(); iter != a.end(); iter++) { cout << *iter << ' '; } cout << endl; return 0;}
参考:
1. 字典序:http://www.cnblogs.com/pmars/p/3458289.html
2. LeetCode原题:https://leetcode.com/problems/next-permutation/
3. C++ vector使用:http://blog.csdn.net/liunian17/article/details/7435781
0 0
- 常见算法问题之NextPermutation
- Leetcode之nextPermutation
- 31NextPermutation
- 31-NextPermutation
- 31-NextPermutation
- 常见的算法问题
- 常见面试算法问题
- 常见算法问题
- 常见算法之排序
- 常见算法问题的分类
- 常见算法问题之最长公共子串问题(Longest common substring problem)
- 常见算法之二分查找
- 常见算法之桶排序
- 数据结构之常见查找算法
- 数据结构之常见排序算法
- 常见算法:c语言矩阵算法问题
- leetcode-31-NextPermutation
- [LeetCode]31.nextPermutation
- 23种设计模式(1)
- RocketMQ双Master模式部署
- com/android/dx/command/dexer/Main:Unsupported major.minor version 52.0 问题
- 前端关注的浏览器状态码
- Java内存分析
- 常见算法问题之NextPermutation
- Codeforece - 630 - D. Hexagons!
- H5学习之路-手机短信验证码的实现
- 面试题8:旋转数组的最小数字
- Swagger与SpringMVC项目整合
- 六、原型模式(Prototype)
- 二叉树
- LeetCode415. Add Strings小学生都会
- Myeclipse调错:The type java.util.Map$Entry cannot be resolved.