Explanation
We can solve this problem recursively. At every index, we look for the smallest number that satisfies the asked condition (i.e., there are no adjacent elements whose difference is 1) and if it satisfies, we add it to our permutation.
For and , we know that no permutation satisfies the asked condition.
Implementation
Time Complexity:
C++
#include <iostream>#include <set>#include <vector>std::vector<int> res;std::set<int> ele;void backtrack(int n) {if ((int)res.size() == n) {for (int x : res) { std::cout << x << " \n"[x == res.back()]; }
Why the above solution runs within Time Limit?
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!