【LeetCode 面试经典150题】46. Permutations 全排列

46. Permutations

题目大意

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

中文释义

对一个包含不重复整数的数组进行排列组合,列出所有可能的排列方式。

示例

  • 示例 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]]

限制条件

  • 1 <= nums.length <= 6
  • -10 <= nums[i] <= 10
  • nums 中的所有整数均唯一。

解题思路

使用深度优先搜索(DFS)来遍历所有可能的排列组合。使用一个哈希表(unordered_map)来记录每个数字是否已经被使用过。

步骤说明

  1. 如果临时数组(temp)的大小与输入数组(nums)相同,则将其添加到答案数组(ans)中。
  2. 遍历每个元素,检查它是否已经被使用过(哈希表中的值为0表示未使用)。
  3. 若未使用,则将其加入到临时数组中,并在哈希表中标记为已使用。
  4. 继续递归调用DFS。
  5. 回溯:将元素从临时数组中移除,并在哈希表中重新标记为未使用。

代码

class Solution {
public:
    vector<int> nums;
    vector<vector<int>> ans;
    vector<int> temp;
    unordered_map<int, int> num_table;

    void dfs() {
        // 步骤1:检查临时数组大小是否与输入数组相等
        if (temp.size() == nums.size()) {
            ans.push_back(temp);
            return;
        }

        for (int i = 0; i < nums.size(); i++) {
            // 步骤2:检查数字是否已经被使用
            if (num_table[nums[i]] == 0) {
                // 步骤3:添加到临时数组并标记为已使用
                temp.push_back(nums[i]);
                num_table[nums[i]] = 1;

                // 步骤4:递归调用DFS
                dfs();

                // 步骤5:回溯
                temp.pop_back();
                num_table[nums[i]] = 0;
            }
        }
    }

    vector<vector<int>> permute(vector<int>& nums) {
        for (int i = 0; i < nums.size(); i++) {
            num_table[nums[i]] = 0;
        }
        this->nums = nums;
        dfs();
        return ans;
    }
};
  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值