46. 全排列
一句话套路used[] 标记,选满 n 个即收集
题目描述
给定一个不含重复数字的数组 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]]
提示:
1 <= nums.length <= 6-10 <= nums[i] <= 10nums中的所有整数 互不相同
思路
时间
O(n·n!)空间
O(n)(不计输出)—— n!=120 时已经不便宜关键点
used[] 标记「这个元素是否已在路径中」;递归到底(path.size()==n)时收集。
撤销顺序必须与选择顺序严格对称
pop 之后要把 used 改回 false。
图解
数组(来自本仓库测试数据,下标从 0 开始)
逐帧动画
1 / 3
快捷键:← → 单步,空格播放 / 暂停。
C++17 题解
namespace lc0046 {
class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> ans;
vector<int> path;
vector<bool> used(nums.size(), false);
dfs(nums, used, path, ans);
return ans;
}
private:
static void dfs(const vector<int>& nums, vector<bool>& used, vector<int>& path,
vector<vector<int>>& ans) {
if ((int)path.size() == (int)nums.size()) { // 选满了 -> 是一个完整排列
ans.push_back(path);
return;
}
for (int i = 0; i < (int)nums.size(); ++i) {
if (used[i]) continue;
used[i] = true;
path.push_back(nums[i]);
dfs(nums, used, path, ans);
path.pop_back(); // 撤销选择
used[i] = false;
}
}
};
}
单元测试
以下用例都在本仓库里实际编译运行过,图解里的数据也取自这里。
lc0046::Solution s;
vector<int> a{1, 2, 3};
CHECK_EQ(s.permute(a),
vector<vector<int>>({{1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2}, {3, 2, 1}}));
vector<int> b{0, 1};
CHECK_EQ(s.permute(b), vector<vector<int>>({{0, 1}, {1, 0}}));
vector<int> c{1};
CHECK_EQ(s.permute(c), vector<vector<int>>({{1}}));