leetcode hot 100 全排列

46. 全排列

已解答

中等

相关标签

相关企业

给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。

class Solution(object):

    def permute(self, nums):

        """

        :type nums: List[int]

        :rtype: List[List[int]]

        """

       

        rtrt=[]

        if len(nums)==0:

            return []

        if len(nums)==1:

            return [nums]

        rt = self.permute(nums[1:])

        for sublist in rt:

            for index,sub in enumerate(sublist):

                rtrt.append(sublist[:index]+ [nums[0]] +sublist[index:])

            rtrt.append(sublist+[nums[0]])

        return rtrt

       

两种递归关系

一种是只用n-1的全排列,n可以放到n-1全排列序列的任意一个位置

第二种是 使用n次n-1的全排列,然后遍历一遍数组,每次都把遍历的数组的数放到n-1全排列的的最前面

我们使用方法一

这个最少的世界复杂度都是阶乘,最终返回的结果的数目也是阶乘的级别的

### LeetCode Hot 100 Problems Python Solutions 以下是针对LeetCode热门100题中的部分经典题目提供Python实现方案: #### 两数之和 (Two Sum) 通过暴力解法可以遍历数组两次来找到目标值对应的索引位置[^1]。 ```python class Solution(object): def twoSum(self, nums, target): for i in range(len(nums)): for j in range(i + 1, len(nums)): if nums[i] + nums[j] == target: return [i, j] return [] ``` 另一种更高效的解决方案是利用哈希表减少时间复杂度至O(n)[^4]: ```python class Solution(object): def twoSum(self, nums, target): hash_map = {} for index, value in enumerate(nums): complement = target - value if complement in hash_map: return [hash_map[complement], index] hash_map[value] = index return [] ``` --- #### 组合总和 (Combination Sum) 此问题可以通过回溯算法解决,递归构建满足条件的结果集[^2]。 ```python class Solution: def combinationSum(self, candidates, target): result = [] def backtrack(remain, comb, start): if remain == 0: result.append(list(comb)) return elif remain < 0: return for i in range(start, len(candidates)): comb.append(candidates[i]) backtrack(remain - candidates[i], comb, i) comb.pop() backtrack(target, [], 0) return result ``` --- #### 全排列 (Permutations) 对于全排列问题,同样采用回溯方法生成所有可能的排列组合。 ```python class Solution: def permute(self, nums): res = [] def backtrack(path, options): if not options: res.append(path[:]) return for i in range(len(options)): path.append(options[i]) backtrack(path, options[:i] + options[i+1:]) path.pop() backtrack([], nums) return res ``` --- #### 最长连续序列 (Longest Consecutive Sequence) 该问题的核心在于使用集合数据结构优化查找效率,从而降低整体的时间复杂度[^3]。 ```python class Solution: def longestConsecutive(self, nums): longest_streak = 0 num_set = set(nums) for num in num_set: if num - 1 not in num_set: current_num = num current_streak = 1 while current_num + 1 in num_set: current_num += 1 current_streak += 1 longest_streak = max(longest_streak, current_streak) return longest_streak ``` --- #### 字符串中所有字母异位词 (Find All Anagrams in a String) 滑动窗口配合字符计数器能够高效解决问题。 ```python from collections import defaultdict class Solution: def findAnagrams(self, s, p): need = defaultdict(int) window = defaultdict(int) valid = 0 for c in p: need[c] += 1 left, right = 0, 0 res = [] while right < len(s): c = s[right] right += 1 if c in need: window[c] += 1 if window[c] == need[c]: valid += 1 while right - left >= len(p): if valid == len(need): res.append(left) d = s[left] left += 1 if d in need: if window[d] == need[d]: valid -= 1 window[d] -= 1 return res ``` --- #### 两数相加 (Add Two Numbers) 链表操作的经典案例之一,需注意进位处理逻辑。 ```python class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def addTwoNumbers(self, l1, l2): dummy_head = ListNode(0) curr = dummy_head carry = 0 while l1 or l2 or carry: x = l1.val if l1 else 0 y = l2.val if l2 else 0 total = x + y + carry carry = total // 10 curr.next = ListNode(total % 10) curr = curr.next if l1: l1 = l1.next if l2: l2 = l2.next return dummy_head.next ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值