A Dynamic Programming Approach to Optimal Planning for Vehicles with Trailers