Subsets —— LeetCode

Given a set of distinct integers, nums, return all possible subsets.

Note:

  • Elements in a subset must be in non-descending order.
  • The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,3], a solution is:

[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

题目大意:给定一个没有重复元素的数组,输出所有子集。

解题思路:直接看代码。

public class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        if(nums == null){
            return res;
        }
        Arrays.sort(nums);
        res.add(new ArrayList<>());
        for(int i=0;i<nums.length;i++){
            int currSize = res.size();
            for(int j=0;j<currSize;j++){
                List<Integer> tmp = new ArrayList<>(res.get(j));
                tmp.add(nums[i]);
                res.add(tmp);
            }
        }
        return res;
    }
}
原文地址:https://www.cnblogs.com/aboutblank/p/4514185.html