fork download
  1.  
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. vector<int> nextGreaterPermutation(vector<int> &A) {
  6. int n = A.size(); // size of the array.
  7.  
  8. // Step 1: Find the break point:
  9. int ind = -1; // break point
  10. for (int i = n - 2; i >= 0; i--) {
  11. if (A[i] < A[i + 1]) {
  12. // index i is the break point
  13. ind = i;
  14. break;
  15. }
  16. }
  17.  
  18. // If break point does not exist:
  19. if (ind == -1) {
  20. // reverse the whole array:
  21. reverse(A.begin(), A.end());
  22. return A;
  23. }
  24.  
  25. // Step 2: Find the next greater element
  26. // and swap it with arr[ind]:
  27.  
  28. for (int i = n - 1; i > ind; i--) {
  29. if (A[i] > A[ind]) {
  30. swap(A[i], A[ind]);
  31. break;
  32. }
  33. }
  34.  
  35. // Step 3: reverse the right half:
  36. reverse(A.begin() + ind + 1, A.end());
  37.  
  38. return A;
  39. }
  40.  
  41. int main()
  42. {
  43. vector<int> A = {2, 1, 5, 4, 3, 0, 0};
  44. vector<int> ans = nextGreaterPermutation(A);
  45.  
  46. cout << "The next permutation is: [";
  47. for (auto it : ans) {
  48. cout << it << " ";
  49. }
  50. cout << "]n";
  51. return 0;
  52. }
  53.  
  54.  
Success #stdin #stdout 0s 5240KB
stdin
Standard input is empty
stdout
The next permutation is: [2 3 0 0 1 4 5 ]n