A Theoretical Analysis of Compositional Generalization in Neural Networks: A Necessary and Sufficient Condition