Permutations II
LeetCode 47 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Backtrack over a frequency map, not over indices.
నేను Permutations II (LeetCode 47) ను ఇలా పరిష్కరించాను — Permutations ప్యాటర్న్లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
With duplicate values, choose from the distinct values that still have remaining copies instead of from positions. A frequency map makes each distinct choice appear once per level, so no duplicates are produced.
Approach
- 1
Counter of values.
- 2
Full length → record.
- 3
For each value with count > 0: use it (count−1), recurse, restore.
నేను ఎలా పరిష్కరించాను
Backtracking on countsPythonO(n·n!) time
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
#maintain the frequency map, if used reduece, reset while backtrack
res=[]
def dfs(comb,cur_freq):
if len(comb)==len(nums):
res.append(comb[:])
return
for num in cur_freq:
if cur_freq[num]>0:
comb.append(num)
cur_freq[num]-=1
dfs(comb,cur_freq)
comb.pop()
cur_freq[num]+=1
dfs([],Counter(nums))
return res
Permutations II — తరచూ అడిగే ప్రశ్నలు
Permutations II వెనుక ఉన్న intuition ఏమిటి?
With duplicate values, choose from the distinct values that still have remaining copies instead of from positions. A frequency map makes each distinct choice appear once per level, so no duplicates are produced.
Permutations II (LeetCode 47) ను ఎలా పరిష్కరించాలి?
1. Counter of values. 2. Full length → record. 3. For each value with count > 0: use it (count−1), recurse, restore.
Permutations II యొక్క time, space complexity ఎంత?
Time: O(n · n!). Space: O(n). (Accepted approach: Backtracking on counts.)
Permutations II లో సాధారణ పొరపాట్లు ఏమిటి?
Iterating the Counter keys means each value is tried once per level.