# Backtracking to find all subsets

• Difficulty Level : Medium
• Last Updated : 17 Aug, 2021

Given a set of positive integers, find all its subsets.
Examples:

```Input: array = {1, 2, 3}
Output: // this space denotes null element.
1
1 2
1 2 3
1 3
2
2 3
3
Explanation: These are all the subsets that
can be formed using the array.

Input: 1 2
Output:
1
2
1 2
Explanation: These are all the subsets that
can be formed using the array.```

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

The iterative solution is already discussed here: the iterative approach to find all subsets. This article aims to provide a backtracking approach.
Approach: The idea is simple, that if there are n number of elements inside an array, there are two choices for every element. Either include that element in the subset or do not include it.
Using the above idea forms a recursive solution to the problem.
Algorithm:

1. Create a recursive function that takes the following parameters, input array, the current index, the output array, or current subset, if all the subsets need to be stored then a vector of the array is needed if the subsets need to be printed only then this space can be ignored.
2. if the current index is equal to the size of the array, then print the subset or output array or insert the output array into the vector of arrays (or vectors) and return.
3. There are exactly two choices for very index.
4. Ignore the current element and call the recursive function with the current subset and next index, i.e i + 1.
5. Insert the current element in the subset and call the recursive function with the current subset and next index, i.e i + 1.

Implementation:

## Java

 `/*package whatever //do not write package name here */` `import` `java.io.*;``import` `java.util.*;``class` `GFG {``    ``public` `static` `void``    ``findSubsets(List> subset, ArrayList nums, ArrayList output, ``int` `index)``    ``{``      ``// Base Condition``        ``if` `(index == nums.size()) {``            ``subset.add(output);``            ``return``;``        ``}``      ` `        ``// Not Including Value which is at Index``        ``findSubsets(subset, nums, ``new` `ArrayList<>(output), index + ``1``);` `        ``// Including Value which is at Index``        ``output.add(nums.get(index));``        ``findSubsets(subset, nums, ``new` `ArrayList<>(output), index + ``1``);``    ``}` `    ``public` `static` `void` `main(String[] args) {``      ` `      ``//Main List for storing all subsets``      ``List> subset = ``new` `ArrayList<>();``      ` `      ``// Input ArrayList``      ``ArrayList input = ``new` `ArrayList<>();``      ``input.add(``1``);``      ``input.add(``2``);``      ``input.add(``3``);``      ` `      ``findSubsets(subset, input, ``new` `ArrayList<>(), ``0``);` `      ``// Comparator is used so that all subset get``      ``// sorted in ascending order of values``        ``Collections.sort(subset, (o1, o2) -> {``            ``int` `n = Math.min(o1.size(), o2.size());``            ``for` `(``int` `i = ``0``; i < n; i++) {``                ``if` `(o1.get(i) == o2.get(i)){``                    ``continue``;``                ``}``else``{``                    ``return` `o1.get(i) - o2.get(i);``                ``}``            ``}``            ``return` `1``;``        ``});``      ` `      ` `      ``// Printing Subset``      ``for``(``int` `i = ``0``; i < subset.size(); i++){``          ``for``(``int` `j = ``0``; j < subset.get(i).size(); j++){``              ``System.out.print(subset.get(i).get(j) + ``" "``);``          ``}``          ``System.out.println();``      ``}``      ` `    ``}``}`

## Python3

 `# Python3 program to find all subsets``# by backtracking.` `# In the array A at every step we have two``# choices for each element either we can``# ignore the element or we can include the``# element in our subset``def` `subsetsUtil(A, subset, index):``    ``print``(``*``subset)``    ``for` `i ``in` `range``(index, ``len``(A)):``        ` `        ``# include the A[i] in subset.``        ``subset.append(A[i])``        ` `        ``# move onto the next element.``        ``subsetsUtil(A, subset, i ``+` `1``)``        ` `        ``# exclude the A[i] from subset and``        ``# triggers backtracking.``        ``subset.pop(``-``1``)``    ``return` `# below function returns the subsets of vector A.``def` `subsets(A):``    ``global` `res``    ``subset ``=` `[]``    ` `    ``# keeps track of current element in vector A``    ``index ``=` `0``    ``subsetsUtil(A, subset, index)``    ` `# Driver Code` `# find the subsets of below vector.``array ``=` `[``1``, ``2``, ``3``]` `# res will store all subsets.``# O(2 ^ (number of elements inside array))``# because at every step we have two choices``# either include or ignore.``subsets(array)` `# This code is contributed by SHUBHAMSINGH8410`

## C++

 `// CPP program to find all subsets by backtracking.``#include ``using` `namespace` `std;` `// In the array A at every step we have two``// choices for each element either  we can``// ignore the element or we can include the``// element in our subset``void` `subsetsUtil(vector<``int``>& A, vector >& res,``                 ``vector<``int``>& subset, ``int` `index)``{``    ``res.push_back(subset);``    ``for` `(``int` `i = index; i < A.size(); i++) {` `        ``// include the A[i] in subset.``        ``subset.push_back(A[i]);` `        ``// move onto the next element.``        ``subsetsUtil(A, res, subset, i + 1);` `        ``// exclude the A[i] from subset and triggers``        ``// backtracking.``        ``subset.pop_back();``    ``}` `    ``return``;``}` `// below function returns the subsets of vector A.``vector > subsets(vector<``int``>& A)``{``    ``vector<``int``> subset;``    ``vector > res;` `    ``// keeps track of current element in vector A;``    ``int` `index = 0;``    ``subsetsUtil(A, res, subset, index);` `    ``return` `res;``}` `// Driver Code.``int` `main()``{``    ``// find the subsets of below vector.``    ``vector<``int``> array = { 1, 2, 3 };` `    ``// res will store all subsets.``    ``// O(2 ^ (number of elements inside array))``    ``// because at every step we have two choices``    ``// either include or ignore.``    ``vector > res = subsets(array);` `    ``// Print result``    ``for` `(``int` `i = 0; i < res.size(); i++) {``        ``for` `(``int` `j = 0; j < res[i].size(); j++)``            ``cout << res[i][j] << ``" "``;``        ``cout << endl;``    ``}` `    ``return` `0;``}`
Output
```1
1 2
1 2 3
1 3
2
2 3
3
```

Complexity Analysis:

• Time Complexity: O(n(2 ^ n)).
For every index i two recursive cases originate, So Time Complexity is O(2^n). If we include the time taken to copy the subset vector into the res vector the time taken will be equal to the size of the subset vector.
• Space Complexity: O(n).
The space complexity can be reduced if the output array is not stored and the static and global variable is used to store the output string.

My Personal Notes arrow_drop_up