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

集合的所有子集(一)

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

    // 1. 确定子集,首先要有开始位置,startIndex;返回值void
    // 2. 递归终结:存储每一个path,然后return即可
    // 3. 单层逻辑:因为要返回子集,所以只要存储每一个path就好呀

import java.util.*;

public class Solution {
    private ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
    private LinkedList<Integer> path = new LinkedList<Integer>();

    public ArrayList<ArrayList<Integer>> subsets(int[] S) {
        // 1. 确定子集,首先要有开始位置,startIndex;返回值void
        // 2. 递归终结:存储每一个path,然后return即可
        // 3. 单层逻辑:因为要返回子集,所以只要存储每一个path就好呀
        Arrays.sort(S);
        getSub(S, 0);
        res.sort(Comparator.comparingInt(ArrayList::size));
        return res;
    }

    private void getSub(int[] S, int startIndex) {
        res.add(new ArrayList(path));

        for (int i = startIndex; i < S.length; ++i) {
            path.add(S[i]);
            getSub(S, i + 1);
            path.removeLast();
        }
    }
}

全部评论

相关推荐

算法冲刺中:kpi面加一,面完完全没动静,感谢信都没有
点赞 评论 收藏
分享
双尔:你就写拥有ai开发经历,熟练运用提示词,优化ai,提高ai回答质量
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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