标签:style blog color io os ar for sp div
problem:
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) { if (num.size() == 0) return; int ind = -1; for (int i = num.size() - 1; i > 0; i--) // 是大于零或者大于等于1 { if (num[i - 1] < num[i]) {ind = i -1;break;} } if (ind == -1) {sort(num.begin(),num.end());return;} int min = INT_MAX, sw = -1; for (int j = num.size() -1; j > ind; j--) { if(num[j] > num[ind] && num[j] < min) { min = num[j]; sw = j;} } int tmp = num[ind]; num[ind] = num[sw]; num[sw] = tmp; vector<int>::iterator it = num.begin(); for(int i = 0; i < ind + 1; i++) { it++; } sort(it, num.end()); return; } };
这题考察什么是词典序的下一个排列。
leetcode第30题--Next Permutation
标签:style blog color io os ar for sp div
原文地址:http://www.cnblogs.com/higerzhang/p/4042071.html