From 5fecc39a13a309a843251fd86dc3248f7e8c0c53 Mon Sep 17 00:00:00 2001 From: "Amisha.Sahu" <115696152+Amisha2093@users.noreply.github.com> Date: Thu, 27 Oct 2022 16:22:19 +0530 Subject: [PATCH] Print all Subsets in Java --- Leetcode-solutions/Subsets.java | 38 +++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Leetcode-solutions/Subsets.java diff --git a/Leetcode-solutions/Subsets.java b/Leetcode-solutions/Subsets.java new file mode 100644 index 0000000..2b283ed --- /dev/null +++ b/Leetcode-solutions/Subsets.java @@ -0,0 +1,38 @@ +// Given an integer array nums of unique elements, return all possible subsets. +// Problem link: https://leetcode.com/problems/subsets/ + +class Solution { + + private List< List > allSubset = new ArrayList< List >(); + private List< Integer > bag = new ArrayList(); + + private void makeSubset(int startIndex, int[] nums){ + + // Add current subset into final result + // Java object is passing by refernce, so we have to make a copy here + allSubset.add(new ArrayList(bag)); + + + // Base cases aka stop condition: + // No more element + if( startIndex == nums.length ){ + return; + } + + //// General cases + // Current level, we choouse element on index i + for( int i = startIndex ; i < nums.length ; i++ ){ + + bag.add( nums[i] ); // put this element into bag + makeSubset(i+1, nums ); // make subset from remaining elements + bag.remove(bag.size()-1); // undo selection + } + return; + + } + public List> subsets(int[] nums) { + + makeSubset(0, nums); + return allSubset; + } +}