回溯法框架下,多种情况如此
全排列
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<int>> permute(vector<int> nums) {
vector<vector<int>> res;
if(nums.size()==0) {
return res;
}
helper(nums, 0, res);
return res;
}
void helper(vector<int> nums, int start, vector<vector<int>>& res) {
if(start==nums.size()-1) {
res.push_back(nums);
return;
}
for(int i=start;i<nums.size();i++) {
swap(nums[i], nums[start]);
helper(nums, start+1,res);
swap(nums[i], nums[start]);
}
}
};
int main() {
vector<int> nums {1,2,3};
vector<vector<int>> res;
Solution s2;
res = s2.permute(nums);
for(auto i:res) {
for(auto j:i){
cout<<j<<" ";
}
cout<<endl;
}
return 0;
}
子集
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<int>> res;
vector<vector<int>> subsets(vector<int>& nums) {
vector<int> track;
backtrace(nums,0,track);
return res;
}
void backtrace(vector<int> &nums, int start, vector<int> & track) {
res.push_back(track);
for(int i= start;i<nums.size();i++) {
track.push_back(nums[i]);
backtrace(nums,i+1,track);
track.pop_back();
}
}
};
int main() {
vector<int> nums {1,2,3};
Solution s2;
vector<vector<int>> res;
res = s2.subsets(nums);
for(auto i:res) {
for(auto j:i) {
cout<<j<<" ";
}
cout<<endl;
}
return 0;
}