expand.grid(a)
(function() as.matrix((expand.grid(a)->x)[do.call(order, x),]))()