Here is a very simple -- but pretty accurate -- analogy.
a) stand by the side of an empty road with a tennis ball. Gently toss the tennis ball straight across the road toward the other side. The ball will move straight across the road.
now, hold the tennis ball again, but this time wait for a truck to approach. Just as the truck passes you, toss the tennis ball in front of the truck. The truck and ball will bounce off each other ... but because the mass of the ball is so much smaller, it will end up flying down the road, ahead of the truck, while the truck slows down by an imperceptible amount.
Ball = spacecraft, truck = planet.
As long as you can arrange things so that a planet is moving in the direction you want to go, this is a really good method of picking up extra speed.