0

I have tried to solve a problem of generating all subsets of an array which contains no duplicates from leetcode : https://leetcode.com/problems/subsets/ . e.g if input is [1,2,3], output should be [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]].

Since we need to generate all subsets, its a backtracking problem. I figured the states, decisions and base cases. Decision will be that we have to include the current element and move forward and next time exclude it and move forward. The code will look like :

vector<vector<int>> subsets(vector<int>& nums) { // nums is our input array
        vector<int> res;
        vector<vector<int>> final_res;
        
        if(nums.empty())
            return {};
        
        subsetsUtil(nums, 0, nums.size(), res, final_res);
        return final_res;
    }
    
    void subsetsUtil(vector<int> &nums, int i, int n, vector<int> res, vector<vector<int>> &final_res) {
        
      if (i == n) {
            final_res.push_back(res);
             return;
        }
        
        res.push_back(nums[i]);
        subsetsUtil(nums, i+1, n, res, final_res); // include
        res.pop_back();
        subsetsUtil(nums, i+1, n, res, final_res);   // exclude
       
    }
};

Now I have changed the implementation of susbsetsUtil and The same problem can be implemented using the for loop in the below code snippet. Is the same approach of include/exclude is used in the for loop ? If yes, I am not able to visualize that how is include/exclude approach is translated to the for loop below. Also are there some good resources to learn about the backtracking patterns and to master it. Thanks !

 void subsetsUtil(vector<int> &nums, int i, int n, vector<int> res, vector<vector<int>> &final_res) {
        
        final_res.push_back(res);
               
        for (int index = i; index < n; index++) {
            res.push_back(nums[index]);
            subsetsUtil(nums, index+1, n, res, final_res);
            res.pop_back();
        }
    }
4
  • Can anybody explain this? Thanks Commented Nov 30, 2020 at 4:40
  • 1. have you tested your first code snippet? 2. is it working? 3. do you understand why / how? Commented Nov 30, 2020 at 10:44
  • 4. (1,2) for the second snippet. ---- see stackoverflow.com/questions/65066122/… for a very similar situation. if you can visualize the first, you'll see the second does the same thing (IIANM). Commented Nov 30, 2020 at 10:53
  • as for the resources, you could browse through this answer of mine, and follow the links in it (also, cis.upenn.edu/~matuszek/cit594-2012/Pages/backtracking.html). there are two c++ links at the bottom of that answer, too. I also once wrote this (search for "maze") but it got reverted. also, this answer. see it any of this helps. Commented Nov 30, 2020 at 11:11

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.