题目
Leetcode 46. 全排列
代码(首刷看解析)
class Solution {
public:
vector<vector<int>> res;
vector<int> track;
vector<bool> used;
vector<vector<int>> permute(vector<int>& nums) {
used.resize(nums.size(), false);
backtrack(nums);
return res;
}
void backtrack(vector<int>& nums) {
if(track.size() == nums.size()) {
res.push_back(track);
return;
}
for(int i = 0; i < nums.size(); i++) {
if(used[i]) continue;
used[i] = true;
track.push_back(nums[i]);
backtrack(nums);
used[i] = false;
track.pop_back();
}
}
};
代码(8.24 二刷自解)
func permute(nums []int) [][]int {
var used []bool
var tmp []int
var res [][]int
used = make([]bool, len(nums))
var backtrack func(nums []int)
backtrack = func(nums []int) {
if len(tmp) == len(nums) {
temp := make([]int, len(tmp))
copy(temp, tmp)
res = append(res, temp)
return
}
for i, v := range nums {
if used[i] == false {
used[i] = true
tmp = append(tmp, v)
backtrack(nums)
used[i] = false
tmp = tmp[:len(tmp)-1]
}
}
}
backtrack(nums)
return res
}
代码(9.15 三刷自解)
class Solution {
public:
vector<int> used;
vector<vector<int>> res;
vector<int> tmp;
vector<vector<int>> permute(vector<int>& nums) {
used.resize(nums.size());
backtrack(nums);
return res;
}
void backtrack(vector<int>& nums) {
if(tmp.size() == nums.size()) {
res.push_back(tmp);
return;
}
for(int i = 0; i < nums.size(); i++) {
if(used[i]) continue;
used[i] = 1;
tmp.push_back(nums[i]);
backtrack(nums);
tmp.pop_back();
used[i] = 0;
}
}
};