回溯-子集

78.子集

给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。

解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。

输入:整型数组
输出:二元列表
思路:利用二进制,(比如说数组长度为3)000、001、010、011、100、101、110、111刚好可以遍历所有情况

class Solution {
    List<List<Integer>> result = new ArrayList<>();
    List<Integer> tempList = new ArrayList<>();
    public List<List<Integer>> subsets(int[] nums) {
        int n = nums.length;
        for(int i = 0; i < (1 << n); i++){
            tempList.clear();
            for(int j = 0; j < n; j++){
                if((i & (1 << j)) != 0){
                    tempList.add(nums[j]);
                }
            }
            result.add(new ArrayList<>(tempList));
        }
        return result;
    }
}

你可能感兴趣的:(java,数据结构,算法)