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.