dynamic programmic solution added. all recursive calls eliminated