Leetcode Hot 100 46.全排列

1.题目

46. 全排列

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

示例 1:

输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

示例 2:

输入:nums = [0,1]
输出:[[0,1],[1,0]]

示例 3:

输入:nums = [1]
输出:[[1]]

2.答案及解析

没写出来 看答案有人用了递归 

好像就是固定一个数字,和其他数字一次交换 然后递归调用自己 ?

比如说5个数字 我固定第一个 和剩下的数字交换

每次交换的时候, 剩下四个数字也这样继续递归 固定第一个然后换

然后剩下3个。。。。  

最后到最后一个的时候 加入到输出里

所以应该是第一次是 第一个数字和第一个数字换 然后dfs(nums.2)

dfs(nums.2)里第二个数字和第二个数字换 然后dfs(nums,3)第三个数字和。。。

第二个和第三个数字换(因为固定了第一个数字 不和第一个换)以此类推吧

然后第二轮for 就是 第一个数字和第二个数字换了之后的数组 然后开头就变成2了 然后递归。。。

反正第一个输出的肯定是原来的数组 因为第一次换的都是自己本身

class Solution {

  • 参数

    • nums:当前排列的数组。

    • x:当前处理的位置。

  • 终止条件

    • 如果 x 等于 nums.size() - 1,说明已经处理完所有位置,将当前排列 nums 加入结果 res

  • 递归过程

    • 遍历从 x 到 nums.size() - 1 的所有位置。

    • 交换 nums[i] 和 nums[x],固定 nums[x],递归处理下一个位置 x + 1

    • 递归返回后,恢复交换(回溯)。

    vector<vector<int>> res;

    void dfs(vector<int> nums,int x){

        if(x==nums.size()-1){

            res.push_back(nums);

            return;

        }

        for(int i=x;i<nums.size();i++){

            swap(nums[i],nums[x]);

            dfs(nums,x+1);

            swap(nums[i],nums[x]);

        }

    }

public:

    vector<vector<int>> permute(vector<int>& nums) {

        dfs(nums,0);

        return res;

    }

};

### 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
发出的红包

打赏作者

码农珊珊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值