Subsets

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],[]]

题目大意:返回给定数组的所有子集,每个子集内元素非降序排列,不允许重复

题目难度:Medium

import java.util.*;

/**
 * Created by gzdaijie on 16/6/3
 * 数组的子集共有2^n个
 * 事实上,0 -> 2^n-1的二进制数就是子集的一种表示方式
 * 二进制的第k位为0,表示子集不含第k个元素,为1则含
 */
public class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        result.add(new ArrayList<Integer>());
        if (nums == null || nums.length == 0) return result;

        int len = nums.length;
        long count = 1 << len;

        Arrays.sort(nums);
        for (int i = 1; i < count; i++) {
            long t = i;
            List<Integer> item = new ArrayList<>();
            for (int j = 0; j < len; j++ , t = t >> 1) {
                if ((t & 1) == 1) item.add(nums[j]);
            }
            result.add(item);
        }
        return result;
    }
}
gzdaijie            updated 2016-06-03 21:53:32

results matching ""

    No results matching ""