(a) Nafi' narrates that Sayyiduna Abdullah bin Umar (may Allah be pleased with them both) said: "Whoever forgets one of his prayers and remembers it while he is praying another prayer behind the imam, then when the imam says the salam, let him pray the prayer he had forgotten, and then after that let him repeat the other prayer."
(b) Ibn Wahb says that Imam Malik, Layth bin Sa'd and Yahya bin Abdullah bin Salim (may Allah have mercy on them) said the same.
(c) Shaykh al-Bayhaqi (may Allah have mercy on him) says: Repeating the other prayer, the one prayed with the imam, is recommended (mustahabb) according to Imam al-Shafi'i (may Allah have mercy on him), not obligatory. And Allah knows best.
Hadith Referenceالسنن الكبرى للبيهقي / كتاب الصلاة / 3195