Learn-dsa..in 30 days!



























CC-8 : Find all subsets of list of numbers.

Description:

Given an array of input numbers, find all subsets of the same.

Test cases and expected outputs:

Input Parameters Expected outputs
Original Array : 1,2,3,4 1234
123
124
12
134
13
14
1
234
23
24
2
34
3
4

Pseudocode:

findSubsets(nums[]):

The array named nums of numbers to be checked is received as input parameter.
Define ArrayList allSubsets to hold list of all subsets found in nums.
Define ArrayList subset to one subset found.
Call findSubsetsDfs(nums, 0, allSubSets, subset).
Return allSubsets.

findSubsetDfs(nums, idx,allSubsets,subset):

If (idx=nums.length):
Add subset to allSubSets.
Return.
Add nums[idx] to subset.
Recursively call findSubsetDfs(nums,idx+1, allSubsets, subset).
Remove last num from subset.
Recursively call findSubsetDfs(nums,idx+1, allSubsets, subset).

Code:

public ArrayList<ArrayList<Integer>> findSubsets(int[] nums) {
	ArrayList<ArrayList<Integer>> allSubsets=new ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> subset = new ArrayList<>();
    findSubsetsDfs(nums,0,allSubsets,subset);
    return allSubsets;
}

private void findSubsetsDfs(int[] nums, int idx, 
		ArrayList<ArrayList<Integer>> allSubsets, ArrayList<Integer> subset) {
	if (idx==nums.length) {
		allSubsets.add(new ArrayList<Integer>(subset));
		return;
	}
	subset.add(nums[idx]);
	findSubsetsDfs(nums,idx+1,allSubsets,subset);
	subset.remove(subset.size()-1);
	findSubsetsDfs(nums,idx+1,allSubsets,subset);
}rn 	Math.max(arr[n-1], findMax(arr,n-1));
}

Click here to download and run code and test cases !