I'm reading this problem and I can understand how they got the output for the first four test cases. But the last one I can't really arrive at it. Is there some mathematical concept that I can apply to get to it instead of just writing a program that counts every permutation by brute force?
Also is there some book on combinatorics that can help me in these types of problems?