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.