Backtracking using combination


  • 0
    D
    class Solution {
    public:
        vector<vector<int>> subsets(vector<int>& nums) {
            int size=nums.size();
    		vector<vector<int>> res;
    		//res.push_back(nums);
    		for(int i=0;i<=size;i++)
    		{
    			calsub(i,size,nums,res);
    		}
    		
    		return res;
        }
    	void calsub(int cur, int size, vector<int> nums, vector<vector<int>> &res)
    	{
    		vector<int> tmp;
    		if(cur==0) {res.push_back(tmp);return;}
    		if(cur==size){res.push_back(nums);return;}
    		calcom(0,0,cur,tmp,nums,res);
    	}
    	void calcom(int start,int pre, int size, vector<int> &tmp,vector<int> nums, vector<vector<int>> &res)
    	{
    		if(start==size){res.push_back(tmp);return;}
    		for(int i=pre;i<(nums.size()-size+tmp.size()+1);i++)
    		{
    			tmp.push_back(nums[i]);
    			calcom(start+1,i+1,size,tmp,nums,res);
    			tmp.pop_back();
    		}
    	}
    
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.