Get all possible subsets from a set of distinct integers.

Given a set of distinct integers, this problem returns all possible subsets that can be formed from those integers. For example, if the input is [1,2,3], the output would be [[3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], []].

Problem

Given a set of distinct integers, return all possible subsets.
Example input:
nums = [1,2,3]
Example output:
[[3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], []]

Solution

This solution is in C++. Our A.I. can create solutions in multiple languages.
by kayakane
#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> result;
        vector<int> temp;
        result.push_back(temp);
        for (int i = 0; i < nums.size(); i++) {
            int size = result.size();
            for (int j = 0; j < size; j++) {
                temp = result[j];
                temp.push_back(nums[i]);
                result.push_back(temp);
            }
        }
        return result;
    }
};

int main() {
    Solution s;
    vector<int> nums = {1, 2, 3};
    vector<vector<int>> result = s.subsets(nums);
    for (int i = 0; i < result.size(); i++) {
        for (int j = 0; j < result[i].size(); j++) {
            cout << result[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

A.I. Evaluation of the Solution

The candidate's solution is complete and solves the problem. The approach is to use a backtracking algorithm to generate all possible subsets.

Evaluated at: 2022-11-22 06:16:00