题目:
全排列
利用used数组标记来实现
class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
vector<int> used(nums.size(), 0);
backtrack(nums,used);
return res;
}
private:
vector<vector<int>> res;
vector<int> re;
void backtrack( vector<int>& nums,vector<int>& used)
{
if(re.size() == nums.size()) {
res.push_back(re);
return;
}
for(int i = 0; i < nums.size(); i++) {
if(used[i] != 0) continue;
else {
re.push_back(nums[i]);
used[i] = 1;
backtrack(nums,used);
re.pop_back();
used[i] = 0;
}
}
}
};
利用交换来实现
class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
backtrack(nums,0);
return c;
}
private:
vector<vector<int>>c;
void backtrack(vector<int>&nums,int n){
if(n==nums.size()){
c.push_back(nums);
}
for(int i=n;i<nums.size();i++){
swap(nums[n],nums[i]);
backtrack(nums,n+1);
swap(nums[n],nums[i]);
}
}
};