Let H denote either the Heisenberg group ℝ2n+1, or the Cartesian product of n copies of the three-dimensional Heisenberg group ℝ3. Let {X1,Y1,... ,Xn,Yn} be an independent set of leftinvariant vector fields on H. In this paper, we study the left-invariant optimal control problem on H with the dynamics q(t) = ∑i=1nui(t)Xi(q(t))+ vi(t)Y(q(t)). the cost functional Λ(q, u) = 1/2∫∑i=1nμi (ui2+vi2), with arbitrary positive parameters μ1,... , μn, and admissible controls taken from the set of measurable functions t → u(t) = (u1(t), v1 (t), ... ,un(t), vn(t)). The above control system is encoded either in the kernel of a contact 1-form (for ℝ2n+1), or in the kernel of a Pfaffian system (for ℝ3n). In both cases, the action of the semi-direct product of the torus Tn with H describe the symmetries of the problem. The Pontryagin maximum principle provides optimal controls; extremal trajectories are solutions to the Hamiltonian system associated with the problem. Abnormal extremals (which do not depend on the cost functional) yield solutions that are geometrically irrelevant. An explicit integration of the extremal equations provides a tool for studying some aspects of the sub-Riemannian structure defined on H by means of the above optimal control problem. © 1999 Kluwer Academic/Plenum Publishers.