Yes, this is possible, and it's not hard once you understand how next_permutation
works.
In short, there are N! permutations of N items. However, only one of them is sorted. 1 2 3 4 5 6 7
for instance is the first of 5040 permutations. Viewed as a string (lexicographically) the next permutation is the one that sorts directly after that: 1 2 3 4 5 7 6
. It particular, the first 5 elements are unaltered. The next permutation alters the 5th element because the last 2 elements are in reverse order.
So, in your case, once you've found an illegal permutation, you'd have to explicitly calculate the next legal permutation by sort order. If 1 2
is the only illegal prefix then 1 3 2 4 5 6 7
is obviously the next valid permutation.
In general, look at your illegal pattern, determine which positions you have to increase because they violate constraints, and come up with the next valid values for those positions (if your pattern is small enough, you can brute-force this). Then fill in the remaining numbers in sorted order.