Striver-SDE-Sheet

Repository containing solution for #SdeSheetChallenge by striver

View the Project on GitHub

Subset Sums

Given a list arr of N integers, print sums of all subsets in it.

Brute force

Recursive Solution

Code

class Solution {
private:
    void subsetSumsRec(int ind, int sum, vector<int> &arr, int N, vector<int> &sumArr)
    {
        // Base condition
        if (ind == N) {
            sumArr.push_back(sum);
            return;
        }

        // pick element - (ind+1,sum+arr[ind])
        subsetSumsRec(ind + 1, sum + arr[ind], arr, N, sumArr);

        // not pick element - (ind+1,sum)
        subsetSumsRec(ind + 1, sum, arr, N, sumArr);
    }

public:
    vector<int> subsetSums(vector<int> arr, int N)
    {
        vector<int> sumArr;
        subsetSumsRec(0, 0, arr, N, sumArr);
        sort(sumArr.begin(), sumArr.end());
        return sumArr;
    }
};