题解 | #集合的所有子集(一)#
集合的所有子集(一)
https://www.nowcoder.com/practice/c333d551eb6243e0b4d92e37a06fbfc9
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param S int整型一维数组 * @return int整型ArrayList<ArrayList<>> */ public ArrayList<ArrayList<Integer>> subsets (int[] S) { // write code here ArrayList<ArrayList<Integer>> res = new ArrayList<>(); ArrayList<Integer> path = new ArrayList<>(); backTrack(path, 0, S, res); res.sort((l1, l2) -> { if (l1.size() != l2.size()) { return Integer.compare(l1.size(), l2.size()); } else { for (int i = 0; i < l1.size(); i++) { if (!l1.get(i).equals(l2.get(i))) { return Integer.compare(l1.get(i), l2.get(i)); } } } return 0; }); return res; } public void backTrack(ArrayList<Integer> path, int index, int [] nums, ArrayList<ArrayList<Integer>> res) { res.add(new ArrayList<>(path)); for (int i = index; i < nums.length; i++) { path.add(nums[i]); backTrack(path, i + 1, nums, res); path.remove(path.size() - 1); } } }#日常刷题#