[LeetCode-interview algorithm classic-Java implementation] [078-Subsets (subset)], leetcode -- java
[078-Subsets (subset )][LeetCode-interview algorithm classic-Java implementation] [directory indexes for all questions]Original question
Given a set of distinct integers, nums, return all possible subsets.
Note:
Elements in a subset must be 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,2,3], [1,3], [2,3], [1,2], []]
Theme
Returns all subsets of a given array of numbers.
Solutions
First, sort the elements in the array, and then use the Recursive Divide and conquer method to solve the problem.
Code Implementation
Algorithm Implementation class
Import java. util. arrayList; import java. util. using list; import java. util. list; public class Solution {private List <Integer> result; private List <Integer> l; private int [] set; private int num; // The number of elements to be selected in the set public List <Integer> subsets (int [] S) {result = new sorted List <> (); if (S! = Null) {l = new ArrayList <> (); // sort S for quickSort (S, 0, S. length-1); set = S; for (int I = 0; I <= S. length; I ++) {num = I; subset (0) ;}// null to accelerate garbage collection set = null; l = null; return result ;} /*** calculate the number of elements as the number of child sets of num ** @ param start among the remaining num elements to be selected, the first minimum subscript */public void subset (int start) {if (num = 0) {List <Integer> tmp = new ArrayList <> (); for (Integer I: l) {tmp. add (I);} result. add (tmp); return;} int endFirst = set. length-num; // The first maximum subscript for (int I = start; I <= endFirst; I ++) {l. add (set [I]); num --; subset (I + 1); num ++; l. remove (new Integer (set [I]);} private void quickSort (int [] arr, int lo, int hi) {if (lo
Evaluation Result
Click the image. If you do not release the image, drag it to a position. After the image is released, you can view the complete image in the new window.
Note Please refer to the following link for more information: http://blog.csdn.net/derrantcm/article/details/47248055]
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.