排列
leecode31,下一个排列。两遍扫描+双指针+分析。
class Solution: def nextPermutation(self, nums: List[int]) -> None: i = len(nums) - 2 while i >= 0 and nums[i]>=nums[i+1]: i -= 1 if i>= 0: j = len(nums)-1 while j>=0 and j > i and nums[i]>=nums[j]: j-=1 nums[i],nums[j] = nums[j],nums[i] left,right = i+1,len(nums)-1 while left < right: nums[left],nums[right] = nums[right],nums[left] left += 1 right -= 1
leecode567,字符串的排列,字典(数组)+滑动窗口,注意滑动窗口滑动后字典(数组)的更新。
class Solution: def checkInclusion(self, s1: str, s2: str) -> bool: a = [ord(x) - ord('a') for x in s1] b = [ord(x) - ord('a') for x in s2] target = [0] * 26 for x in a: target[x] += 1 window = [0]*26 for i,x in enumerate(b): window[x] += 1 if i>=len(a): window[b[i-len(a)]] -= 1 if window == target: return True return False
leecode60,排列序列,数学方法
class Solution: def getPermutation(self, n: int, k: int) -> str: factor = [1] for i in range(1,n): factor.append(factor[-1]*i) k -= 1 ans = [] valid = [1]*(n+1) for i in range(1,n+1): order = k//factor[n-1] + 1 for j in range(1,n+1): order -= valid[j] if order == 0: valid[j] = 0 ans.append(str(j)) break k %= factor[n-1] return "".join(ans)