"078-subsets (subset)""leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"Original Question
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 = [A/b], a solution is:
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], []]
Main Topic
Given an array of different numbers, return all of its subsets.
Thinking of solving problems
First, the elements in the array are sorted, and then the recursive division method is used to solve them.
Code Implementation
Algorithm implementation class
ImportJava.util.ArrayList;ImportJava.util.LinkedList;ImportJava.util.List; Public class solution { Privatelist<list<integer>> result;PrivateList<integer> l;Private int[] set;Private intNum//The number of selected elements that are required in set PublicList<list<integer>>subsets(int[] S) {result =NewLinkedlist<> ();if(S! =NULL) {L =NewArraylist<> ();//Sort S to be processedQuickSort (S),0, S.length-1); set = S; for(inti =0; I <= s.length; i++) {num = i; Subset (0); } }//Empty for faster garbage collectionSet =NULL; L =NULL;returnResult }/** * The number of elements is a subset of NUM * * @param start the remaining selected NUM elements, the first of the smallest subscript */ Public void subset(intStart) {if(num = =0) {list<integer> TMP =NewArraylist<> (); for(Integer i:l) {tmp.add (i); } result.add (TMP);return; }intEndfirst = Set.length-num;//remainder of NUM elements to pick, the first one is the largest subscript for(inti = start; I <= Endfirst; i++) {L.add (set[i]); num--; Subset (i +1); num++; L.remove (NewInteger (Set[i])); } }Private void QuickSort(int[] arr,intLointHi) {if(Lo < HI) {intMid = Getmid (arr, lo, HI); QuickSort (arr, lo, mid-1); QuickSort (arr, Mid +1, HI); } }Private int Getmid(int[] arr,intLointHi) {intTMP = Arr[lo]; while(Lo < HI) { while(Lo < hi && Arr[hi] > tmp) {hi--; } Arr[lo] = Arr[hi]; while(Lo < hi && Arr[lo] < TMP) {lo++; } Arr[hi] = Arr[lo]; } Arr[lo] = tmp;returnLo }}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Special InstructionsWelcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47248055"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode-Interview algorithm classic-java Implementation" "078-subsets (subset)"