题解 | #集合的所有子集(一)#

集合的所有子集(一)

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);
        }
    }
}

#日常刷题#
全部评论

相关推荐

小浪_Coding:找硬件测试,也可兼顾软测欧, 简历还可以的 ,注意排版,项目写的有条理一点, 然后个人技能多加点, 润色好简历之后就开始沟通海投了,深圳,东莞这边做硬件相关的公司还不少, 医疗类,仪器类的都可以尝试
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务