This problem is straightforward. Generate all permutations of , check is is a subsequence and count how many swap occurred. If swap count is less or equal to then increment the answer. To generate all permutations, in you can use std::next_permutation(). Total Complexity will be .