Title:
Given a set of distinct integers, nums, return all possible subsets.
Note:
- Elements in a subset must is in non-descending order.
- The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,3] , a solution is:
[ 3], [1], [2], [1,3], [+] , [2,3], [up ], []]
Test Instructions:
Given an array of different numbers, Nums returns all the subsets in this array.
Attention:
1. The elements in the sub-set must be in ascending order
2. The final result cannot contain a duplicate subset.
Algorithm Analysis:
Combined with the previous question "combinations" method, the previous question as a sub-function to use.
AC Code:
<span style= "Font-family:microsoft yahei;font-size:12px;" >public class Solution {public arraylist<arraylist<integer>> subsets (int[] nums) {ArrayList <ArrayList<Integer>> fres = new arraylist<arraylist<integer>> (); arraylist<integer> flist= new arraylist<integer> (); Arrays.sort (Nums); Fres.add (flist); for (int i=1;i<=nums.length;i++) {arraylist<arraylist<integer>> sres = new Arraylist<array List<integer>> (); Sres=combine (Nums, i); Fres.addall (Sres); } return fres; } public static arraylist<arraylist<integer>> combine (int nums[], int k) {Arraylist<arraylis t<integer>> res = new arraylist<arraylist<integer>> (); if (nums.length<=0 | | nums.length<k) return res; Helper (Nums,k,0,new arraylist<integer> (), res); return res; } private static void helper (int nums[], int k, int start, arraylist<integer> item, ARRAYLIST<ARRAYLIST<INTEGER>> ; RES) {if (Item.size () ==k) {Res.add (new arraylist<integer> (item)); Return } for (int i=start;i<nums.length;i++)//try per possibility number in current position {I Tem.add (Nums[i]); Helper (nums,k,i+1,item,res); After selecting number for the current position, process next position item.remove (Item.size ()-1); Clear the current position to try next possible number}}}</span>
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode] [Java] Subsets