Permutations
LeetCode 46 · मध्यम · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू
Fix position start, swap each choice into it.
मी 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
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.
मी कसा सोडवला · पहिल्या कल्पनेपासून अंतिम उपायापर्यंत
Append unused numbers.
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 resSwap 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 resPermutations — वारंवार विचारले जाणारे प्रश्न
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.