Tensorum
YouTubeसीखना शुरू करें
LeetCode 47 · Permutations

Permutations II

LeetCode 47 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू

Backtrack over a frequency map, not over indices.

मध्यमArrayBacktrackingSorting

मैंने 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. 1

    Counter of values.

  2. 2

    Full length → record.

  3. 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.