Python, 7773
def f(x,t=0):
t=0
if x:t=f(x-1)-x;t=t+2*x*;t+=2*x*(t*(t>0)in map(f,range(x)))
return t
Edit 1: Thanks to @xnor's tips on the other Python answer! (I just realised that both look very similar.)
Does anyone know of some way to reduce the number of all those spaces and tabs?Edit 2: Thanks again, @xnor.