A Method for Solving the Problem of Optimal Switching