这是一个典型的深度优先搜索问题
class Solution { private: void dfs(vector<int>& tmp,vector<vector<int>>& ans,vector<int>& nums,int depth,int n){ if(depth==n){ ans.push_back(tmp); return; } tmp.push_back(nums[depth]); dfs(tmp,ans,nums,depth+1,n); tmp.pop_back(); dfs(tmp,ans,nums,depth+1,n); } public: vector<vector<int>> subsets(vector<int>& nums) { vector<vector<int>> ans; vector<int> tmp; int n=nums.size(); dfs(tmp,ans,nums,0,n); return ans; } };
#include "stdafx.h" #include "vector" #include "iostream" using namespace std; int _tmain(int argc, _TCHAR* argv[]) { vector<int> vct; vector<vector<int>> cap; cap.push_back(vct); cap.push_back(vct); cout<<cap.size()<<endl;//此时输出为2,即使是空的容器,也占用一个位置 return 0; }