C++20 sections · 1024 units
Open in Course

Permutation Example

Trying all orders

I'll show you how to solve problems by trying every permutation. Sort your vector first: sort(v.begin(), v.end()) to start from the lexicographically smallest arrangement. Then loop: do { check_solution(v); } while (next_permutation(v.begin(), v.end())); tests every possible ordering.

The do-while ensures the initial sorted order is checked. Use this approach for small inputs only. Permutations grow factorially, making this brute force approach infeasible for n>10n > 10 elements due to time limits.