题解 | #集合的所有子集#

集合的所有子集

http://www.nowcoder.com/practice/c333d551eb6243e0b4d92e37a06fbfc9

import java.util.*;

public class Solution {
    public static ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
    public ArrayList<ArrayList<Integer>> subsets(int[] S) {
        ArrayList<Integer> track = new ArrayList<>();
        Arrays.sort(S);
        dfs(S, 0, track);
        Collections.sort(res,(o1,o2)->{
            return o1.size()-o2.size();
        });
        return res;
    }
    public void dfs(int[] arr, int index, ArrayList<Integer> temp){
        //if(index>=arr.length) return;
        res.add(new ArrayList<Integer>(temp));
        for(int i=index;i<arr.length;i++){
            temp.add(arr[i]);
            dfs(arr,i+1,temp);
            temp.remove(temp.size()-1);
        }
    }
}

回溯后对输出按照元素的长度排个序

全部评论

相关推荐

03-27 15:39
算法工程师
几乎所有大中厂都挂了,现在压力拉满了。。。
下辈子转生为少女乐队女主人公:同全挂,想去考研逃避现实了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务