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
)来记录每个数字是否已经被使用过。
步骤说明
- 如果临时数组(
temp
)的大小与输入数组(nums
)相同,则将其添加到答案数组(ans
)中。 - 遍历每个元素,检查它是否已经被使用过(哈希表中的值为0表示未使用)。
- 若未使用,则将其加入到临时数组中,并在哈希表中标记为已使用。
- 继续递归调用DFS。
- 回溯:将元素从临时数组中移除,并在哈希表中重新标记为未使用。
代码
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;
}
};