C++回溯求数组所有子集

tech2022-07-27  177

#include<iostream> #include<vector> using namespace std; vector<vector<int>> vec; void backtrace(vector<int>& nums,vector<int>& path, int pos) { vec.push_back(path); for(int i=pos;i<nums.size();i++) { path.push_back(nums[i]); backtrace(nums,path,i+1); path.pop_back(); } } vector<vector<int>> subSet(vector<int>& nums) { vector<int> path; backtrace(nums,path,0); return vec; } int main() { vector<int> nums={1,2,3}; vector<vector<int>> ans=subSet(nums); for(int i=0;i<ans.size();i++) { for(int j=0;j<ans[i].size();j++) { cout<<ans[i][j]<< " "; } cout<<endl; } return 0; }

最新回复(0)