C++ concise dfs solution


  • 0
    H
    class Solution {
    public:
        vector<vector<int> > subsets(vector<int> &nums) {
        	vector<vector<int>> result;
        	vector<int> data;
        	sort(nums.begin(), nums.end());
        	dfs(nums, 0, result, data);
        	return result;
        }
        void dfs(vector<int>& nums, int start, vector<vector<int>>& result, vector<int>& data) {
            if (start> nums.size() - 1) {
                result.push_back(data);
                return;
            }
            // not choose nums[start]
            dfs(nums, start+1, result, data);
            // choose nums[start]
            data.push_back(nums[start]);
            dfs(nums, start+1, result, data);
            data.pop_back();
        }
    
    };
    

Log in to reply
 

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