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.