78 - Subsets & 90 - Subsets II

78 - Subsets

#medium
Given an integer array nums of unique elements, return all possible subsets

(the power set).

The solution set must not contain duplicate subsets. Return the solution in any order.

Example 1:
Input: nums = [1,2,3]
Output: [ [],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3] ]

Example 2:
Input: nums = [0]
Output: [ [],[0] ]

class Solution {
public:
    vector<vector<int>> result;
    vector<int> path;
    void backtracking( vector<int> & nums, int startIndex ) {
        result.push_back(path);
        for ( int i = startIndex; i < nums.size(); i++ ) {
            path.push_back(nums[i]);
            backtracking(nums, i + 1);
            path.pop_back();
        }

    }

    vector<vector<int>> subsets(vector<int>& nums) {
        backtracking( nums, 0 );    
        return result;
    }

};

90 - Subsets II

#medium

Given an integer array nums that may contain duplicates, return all possible subsets (the power set)_.

The solution set must not contain duplicate subsets. Return the solution in any order.

Example 1:
Input: nums = [1,2,2]
Output: [ [],[1],[1,2],[1,2,2],[2],[2,2] ]

Example 2:
Input: nums = [0]
Output: [ [],[0] ]

class Solution {
public:
    vector<vector<int>> result;
    vector<int> path;

    void backtracking( vector<int> nums, int startIndex, vector<bool> & used ) {
        result.push_back( path );
        for ( int i = startIndex; i < nums.size(); i++ ) {
            // used[i - 1] == true,說明同一樹枝candidates[i - 1]使用過
            // used[i - 1] == false,說明同一[樹層]candidates[i - 1]使用過
            // 而我們要對同一[樹層]使用過的元素進行跳過
            if ( i >= 1 && nums[i] == nums[i-1] && used[i-1] == false ) continue;
            path.push_back( nums[i] );
            used[i] = true;
            backtracking( nums, i + 1, used );
            used[i] = false;
            path.pop_back();
        }

    }

    vector<vector<int>> subsetsWithDup(vector<int>& nums) {
        sort( nums.begin(), nums.end() );
        vector<bool> used( nums.size(), false );
        backtracking( nums , 0, used );
        return result;
    }
};