From 5756b5e1142613686e54480db363cc4a6da0fc52 Mon Sep 17 00:00:00 2001 From: Ashish Kumar Rastogi <83218800+Ashishr1234@users.noreply.github.com> Date: Sat, 1 Oct 2022 19:51:28 +0530 Subject: [PATCH] Create Next Permutation algo --- Next Permutation algo | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Next Permutation algo diff --git a/Next Permutation algo b/Next Permutation algo new file mode 100644 index 00000000..59dd2c26 --- /dev/null +++ b/Next Permutation algo @@ -0,0 +1,24 @@ + +class Solution { +public: + void nextPermutation(vector &num) + { + if (num.empty()) return; + + // in reverse order, find the first number which is in increasing trend (we call it violated number here) + int i; + for (i = num.size()-2; i >= 0; --i) + { + if (num[i] < num[i+1]) break; + } + + // reverse all the numbers after violated number + reverse(begin(num)+i+1, end(num)); + // if violated number not found, because we have reversed the whole array, then we are done! + if (i == -1) return; + // else binary search find the first number larger than the violated number + auto itr = upper_bound(begin(num)+i+1, end(num), num[i]); + // swap them, done! + swap(num[i], *itr); + } +};