题解 | #集合的所有子集(一)# 脑瘫暴力
集合的所有子集(一)
https://www.nowcoder.com/practice/c333d551eb6243e0b4d92e37a06fbfc9
import java.util.*; public class Solution { Map<Integer, ArrayList<Integer>> resultMap = new HashMap<>(); // 数组哈希值 public int arrHash(ArrayList<Integer> arr) { if(arr.size() == 0){ return -9999; } int len = arr.size(); int sum = 0; for (int i = 0; i < len; i++) { sum = (sum+1) * 10 + arr.get(i); } System.out.println("数组" + arr.toString() + " | 哈希值:" + sum); return sum; } void dfs(int[] arr, int idx, ArrayList<Integer> t) { resultMap.put(arrHash(t), t); if (idx >= arr.length) return; // 加入 ArrayList<Integer> newArr2 = new ArrayList<>(t); newArr2.add(arr[idx]); dfs(arr, idx + 1, newArr2); // 不加入 ArrayList<Integer> newArr1 = new ArrayList<>(t); dfs(arr, idx + 1, newArr1); } public ArrayList<ArrayList<Integer>> subsets (int[] S) { Arrays.sort(S); dfs(S, 0, new ArrayList<>()); ArrayList<ArrayList<Integer>> returnData = new ArrayList<>(); for (Integer key : resultMap.keySet()) { returnData.add(resultMap.get(key)); } Collections.sort(returnData, new Comparator<ArrayList<Integer>>() { public int compare(ArrayList<Integer> p1, ArrayList<Integer> p2) { if(p1.size() == p2.size()){ return p1.get(p1.size()-1) < p2.get(p2.size()-1) ? -1:1; } return p1.size() < p2.size() ? -1:1; } }); return returnData; } }
优化?什么优化?