Let H denote either the Heisenberg group \Bbb R^{2n+1}, or the Cartesian product of n copies of the three-dimensional Heisenberg group \Bbb R^3. Let lX1, Y1, …, Xn, Ynr be an independent set of left-invariant vector fields on H. In this paper, we study the left-invariant optimal control problem on H with the dynamics \dot{q}(t)=\sum\limits^n_{i=1}u_i(t)X_i(q(t))+v_i(t)Y(q(t)), the cost functional \Lambda(q,u)={1 \over 2}\int \sum\limits^n_{i=1}\mu_i(u^2_i+v^2_i), with arbitrary positive parameters μ1, …, μn, and admissible controls taken from the set of measurable functions t\mapsto u(t)=(u_1(t),v_1(t),\ldots , u_n(t), v_n(t)). The above control system is encoded either in the kernel of a contact 1-form (for \Bbb R^{2n+1}), or in the kernel of a Pfaffian system (for \Bbb R^{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 controlss 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.