A reverse version of the Dictionary algorithm :) If you AC-ed "Next Permutation II", copy it over and just reverse the conditions.
class Solution {
public:
/**
* @param nums: An array of integers
* @return: An array of integers that's previous permuation
*/
vector<int> previousPermuation(vector<int> &num) {
size_t len = num.size();
if(len < ) return num; // step 1: find first up-side from back
int i = len - ;
while (i > )
{
if (num[i - ] > num[i]) break;
i--;
} // step 2: find last num smaller than num[i-1]
int j = i;
while (j < len)
{
if (num[j] >= num[i - ]) break;
j++;
}
j--; // step 3: replace num[i-1] and num[j]
if(i > )
std::swap(num[i-], num[j]); // step 4: reverse all after i
std::reverse(num.begin() + i, num.end());
return num;
}
};