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:java
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
給定一個不一樣數字的數組,返回它的全部子集。算法
先對數組中的元素進行排序,而後再用遞歸分治法進行求解。數組
算法實現類ui
import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class Solution { private List<List<Integer>> result; private List<Integer> l; private int[] set; private int num; // 在set中還須要的選擇的元素個數 public List<List<Integer>> subsets(int[] S) { result = new LinkedList<>(); if (S != null) { l = new ArrayList<>(); // 對S進行排序處理 quickSort(S, 0, S.length - 1); set = S; for (int i = 0; i <= S.length; i++) { num = i; subset(0); } } // 賦空,加快垃圾回收 set = null; l = null; return result; } /** * 求元素個個數是num的子集數 * * @param start 剩餘的要挑選的num個元素中,第一個的最小下標 */ 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; // 剩餘的要挑選的num個元素中,第一個的最大下標 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 < hi) { int mid = getMid(arr, lo, hi); quickSort(arr, lo, mid - 1); quickSort(arr, mid + 1, hi); } } private int getMid(int[] arr, int lo, int hi) { int tmp = 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; return lo; } }