Subsets solution


  • 0
    V

    For every element, you have 2 options. You may either include the element in your subset or you will not include the element in your subset.
    Make the call for both the cases.

    public static List<List<Integer>> subsets(int[] nums) 
        {
    		 List<List<Integer>> res = new ArrayList<List<Integer>>();
    		 res.add(new ArrayList<Integer>());
    		 boolean b[] = new boolean[nums.length];
    		 for(int i=0;i<nums.length;i++)
    		 {
    			 if(!b[i])
    			 {
    				 ArrayList<Integer> a = new ArrayList<Integer>();
    				 b[i] = true;
    				 a.add(nums[i]);
    				 res.add(new ArrayList<Integer>(a));
    				 check(i,a,res,b,nums);
    				 b[i] = false;
    			 }
    		 }
    		 return res;
        }
    	private static void check(int start, ArrayList<Integer> a, List<List<Integer>> res, boolean[] b, int nums[]) 
    	{
    		if(start==nums.length-1)
    			return;
    		for(int i=start+1;i<nums.length;i++)
    		{
    			if(!b[i])
    			 {
    				 b[i] = true;
    				 a.add(nums[i]);
    				 res.add(new ArrayList<Integer>(a));
    				 check(i,a,res,b,nums);
    				 b[i] = false;
    				 a.remove(new Integer(nums[i]));
    				 
    			 }
    		}
    	}
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.