ByteDance interview question

Permutation question from leetcode (BackTracking)