Stabilization of switched systems via optimal control