Recursive backtracking solution