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.