算法小白,最近刷LeetCode。希望能够结合自己的思考和别人优秀的代码,对题目和解法进行更加清晰详细的解释,供大家参考^_^
Given a collection of distinct numbers, return all possible permutations.
For example,
[1,2,3] have the following permutations:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
全排列问题:题目让输出给定的n个不同数字的全排列,这里使用递归的方法,每次增加一个元素,将这个元素从候选集中移除,递归的重复上述过程,当序列长度达到n时,递归函数返回。直接看代码:
class Solution {
public:
// 递归函数:len是目标序列长度,candi是当前的候选集合,tmp是正在生成的序列,res是最终结果
void fun(const int &len, vector<int> candi, vector<int> tmp, vector<vector<int>> &res) {
if (tmp.size() == len) res.push_back(tmp); // tmp长度够了,说明已经生成了一个排列,加入到结果集res中
else {
for (int i = 0; i < candi.size(); ++i){
vector<int> tmp_2(tmp); // 保存当前序列,复制一个临时序列作为下次递归的参数
tmp_2.push_back(candi[i]); // 选中一个元素,加入到序列中
int j = 0;
vector<int> tmp_candi(candi); // 同上,保存当前的候选集,复制一个新的临时候选集
for (auto tmp_iter = tmp_candi.begin(); tmp_iter < tmp_candi.end(); ++tmp_iter, ++j){
if (j == i) tmp_candi.erase(tmp_iter); // 从临时候选集中移除之前选中的元素
}
// 使用之前创建的临时变量进行递归,
fun(len, tmp_candi, tmp_2, res);
}
}
}
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> res;
vector<int> tmp;
fun(nums.size(), nums, tmp, res);
return res;
}
};
笔者认为,这种递归方式最主要的是要保存好当前的状态,代码中tmp_2
和tmp_candi
的使用都是为了保存当前递归的状态。