vector ans(n+1);

ans[0]=1;

for(int i=1;i<=n;i++)

ans[i] = ans[i-1]*(n-i+1)/i;

this is enough.

vector ans(n+1);

ans[0]=1;

for(int i=1;i<=n;i++)

ans[i] = ans[i-1]*(n-i+1)/i;

this is enough.

What is the formula or consept behind this solution?

It provides better complexity for both time and space.