Skip to content

Instantly share code, notes, and snippets.

@zhoutuo
Last active December 13, 2015 22:08
Show Gist options
  • Save zhoutuo/4981816 to your computer and use it in GitHub Desktop.
Save zhoutuo/4981816 to your computer and use it in GitHub Desktop.
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…
class Solution {
public:
void nextPermutation(vector<int> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
bool found = false;
int left = -1;
int right = num.size();
for(int i = num.size() - 1; i >= 0; --i) {
int cur = num[i];
for(int j = i - 1; j >= 0; --j) {
if(num[j] < num[i] && j >= left) {
found = true;
if(left == j) {
right = num[right] > num[i] ? i : right;
} else {
right = i;
}
left = j;
break;
}
}
}
if(!found) {
sort(num.begin(), num.end());
return;
}
swap(num[left], num[right]);
sort(num.begin() + left + 1, num.end());
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment