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

Permutations

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

Fix position start, swap each choice into it.

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

ನಾನು Permutations (LeetCode 46) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Permutations ಪ್ಯಾಟರ್ನ್‌ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.

ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್‌ನಲ್ಲಿದೆ.

Intuition

A permutation picks every element exactly once, in some order. Either build it by appending unused numbers, or generate in place by swapping each candidate into the current position and recursing on the rest.

Approach

  1. 1

    Version 1: append any number not yet in the list.

  2. 2

    Version 2: for i from start, swap nums[i] into position start.

  3. 3

    Recurse for start + 1, then swap back.

  4. 4

    Record when start reaches n.

ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ · ಮೊದಲ ಆಲೋಚನೆಯಿಂದ ಅಂತಿಮ ಪರಿಹಾರದವರೆಗೆ

1
Build with membership checkO(n²·n!) time

Append unused numbers.

2
Swap in placeAcceptedO(n·n!) time

No extra used-array.

Build with membership checkPythonO(n²·n!) time
class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        res=[]
        def dfs(index,ds):
            if index == len(nums):
                res.append(ds[:])
            for num in nums:
                if num not in ds:
                    ds.append(num)
                    dfs(index+1,ds)
                    ds.pop()
        dfs(0,[])
        return res
Swap in placePythonO(n·n!) time
class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        res=[]
        def dfs(start,ds):
            if start == len(nums):
                res.append(ds[:])
            for i in range(start,len(nums)):
                nums[i],nums[start]=nums[start],nums[i]
                dfs(start+1,nums)
                nums[start],nums[i]=nums[i],nums[start]
        dfs(0,[])
        return res
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

Permutations — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು

Permutations ಹಿಂದಿನ intuition ಏನು?

A permutation picks every element exactly once, in some order. Either build it by appending unused numbers, or generate in place by swapping each candidate into the current position and recursing on the rest.

Permutations (LeetCode 46) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?

1. Version 1: append any number not yet in the list. 2. Version 2: for i from start, swap nums[i] into position start. 3. Recurse for start + 1, then swap back. 4. Record when start reaches n.

Permutations ನ time ಮತ್ತು space complexity ಎಷ್ಟು?

Time: O(n · n!). Space: O(n). (Accepted approach: Swap in place.)

Permutations ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?

`num not in ds` costs O(n) and breaks with duplicate values.

Permutations ಅನ್ನು ಪರಿಹರಿಸಲು ಒಂದಕ್ಕಿಂತ ಹೆಚ್ಚು ಮಾರ್ಗಗಳಿವೆಯೇ?

Build with membership check (O(n²·n!) time): Append unused numbers. Swap in place (O(n·n!) time): No extra used-array.