Recursion & Backtracking
Subsets, combinations, permutations, constraint search — ఎంచుకో, అన్వేషించు, వెనక్కి తీసుకో.
DSAమధ్యస్థ స్థాయి21 గంటలు8 ప్యాటర్న్లు · 28 ప్రాబ్లమ్స్
0%
మీ పురోగతిప్రాబ్లమ్, కేస్ స్టడీ పేర్లు, కోడ్, సాంకేతిక కీవర్డ్లు ఇంగ్లీష్లోనే ఉంచాం.
మూల ఆలోచన
సమాధానాన్ని క్రమంగా నిర్మించండి; ప్రతి దశలో ప్రతి valid ఎంపికను ప్రయత్నించి, recurse చేసి, తర్వాత undo చేయండి. Constraints అనుమతించినంత త్వరగా prune చేయండి.
ఎప్పుడు వాడాలి
- అన్ని subsets, permutations లేదా combinations తయారు చేయడం
- Constraint satisfaction (N-Queens, Sudoku)
- Grid లో పదాలు లేదా paths వెతకడం
టెంప్లేట్
def subsets(nums):
res, path = [], []
def go(i):
if i == len(nums):
res.append(path[:])
return
path.append(nums[i]); go(i + 1); path.pop() # take
go(i + 1) # skip
go(0)
return resComplexity
స్వభావరీత్యా exponential — O(2ⁿ) subsets, O(n!) permutations; అసలు ఖర్చును pruning నిర్ణయిస్తుంది.
సాధారణ పొరపాట్లు
- Copy బదులు live path ను జోడించడం
- Sort తర్వాత duplicates ను దాటవేయకపోవడం
- ప్రతి exit path లో state undo చేయడం మర్చిపోవడం
ఈ కోర్సులోని ప్యాటర్న్లు
గుర్తించే సంకేతాలు
SubsetsCombinationsPermutationsConstraint SearchGrid Search