Saturday, June 25, 2016

90. Subsets II

Same as "78. Subsets" except checking whether a new element is a duplicate.

1:  class Solution {  
2:  public:  
3:    vector<vector<int>> subsetsWithDup(vector<int>& nums) {  
4:      sort(nums.begin(), nums.end());  
5:      vector<vector<int>> res;  
6:      vector<int> sol;  
7:      res.push_back(sol);  
8:      helper(nums, 0, sol, res);  
9:      return res;  
10:    }  
11:    void helper(vector<int> &nums, int start, vector<int> &sol, vector<vector<int>> &res) {  
12:      for (int i = start; i < nums.size(); i++) {  
13:        if (i == start || nums[i] != nums[i-1]) {  
14:          sol.push_back(nums[i]);  
15:          res.push_back(sol);  
16:          helper(nums, i+1, sol, res);  
17:          sol.pop_back();  
18:        }  
19:      }  
20:    }  
21:  };  

No comments:

Post a Comment