working solution up to 4, needs optimization (memoization??) for larger limit