Abstract Extending the histogram method of Ferrenberg and Swendsen to the problem of a SAW in a bad solvent, we obtain a new expression for the free energy of such a system, which fits very properly the numerical results of our Monte Carlo simulations. The basic difference with Flory's theory lies in the reference system: instead of considering random walks (RW) we start with self-avoiding walks (SAW) for which we already proposed a model expression for the distribution of the radius of gyration. This distribution is universal for any class of homo- or heteropolymers and contains all the information concerning the excluded volume problem. For homopolymers we consider the standard case where attractive nearest neighbours interactions simulate a bad solvent. At a given radius of gyration r we compute the density of states P(r, m) for an interacting self avoiding walk (ISAW) as a function of its number of contacts m. We build a microscopic phenomenology for P(r, m) based on a factorisation procedure: P(r, m) is split into an a priori probability P(r) of finding a SAW with a given r, and a conditional probability P(m/r) of finding such a conformation with m contacts. A complete scaling is given for P(r) whereas P(m/r) is found to be well approximated by a gaussian distribution. Scaling laws for the first two cumulants of P(m/r) are exhibited from a finite-size scaling analysis. The theta-point temperature is recovered along with its dependence on the polymer length and the free energy of the globule phase is well reproduced. This approach is shown to be generalizable to heteropolymers by merely replacing m by u, the energy per monomer, and computing the density of states P(r, u) at a given r. The case of sequenced and random copolymers is examined with special attention to polyampholytes.