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.