Optimization of proton and heavy ion therapy using an adaptive inversion algorithm