Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 47 · Permutations

Permutations II

LeetCode 47 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

Backtrack over a frequency map, not over indices.

ಮಧ್ಯಮArrayBacktrackingSorting
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು 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.