From wikia:
In the episode "The Hot Tub Contamination", the origins of this knocking ritual are revealed. When Sheldon was 13 years old, he once came home because they ran out of math to teach him. His mother was at a Bible study. He walked in the house expecting it to be empty and heard a sound from his parents' bedroom. When he opened the door, he saw his father having relations with another woman. It’s why he never opens a door without knocking three times. The first one is traditional, but two and three are for people to get their pants on.
Because Wikia is, well, Wikia, here's a link to a more reliable transcript of the episode:
https://www.springfieldspringfield.co.uk/view_episode_scripts.php?tv-show=big-bang-theory&episode=s10e05 link