O(n^2) backtracking solution