LeetCode-78. Subsets

来源:互联网 发布:在淘宝刷好评犯法吗 编辑:程序博客网 时间:2024/06/05 07:00

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

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

在给定的一个元素各不相同集合中查找子集合。

为了保证子集合的唯一性,可以设置一个位置参数pos,每次从该位置开始DFS。

对于一个集合[1,2,3],其子集合的构成一定是空元素的集合、1个元素的集合、2个元素的集合,3个元素的集合。

package solutions._78;import java.util.ArrayList;import java.util.LinkedList;import java.util.List;/** * 78. Subsets */class Solution {    private List<List<Integer>> result;    private List<Integer> cur;    private boolean[] visited;    private void DFS(int[] nums, int n, int pos) {        if (n == cur.size()) {            result.add(new ArrayList<>(cur));            return;        }        for (int i = pos; i < nums.length; i++) {            if (!visited[i]) {                visited[i] = true;                cur.add(nums[i]);                DFS(nums, n, i);                visited[i] = false;                cur.remove(cur.size() - 1);            }        }    }    public List<List<Integer>> subsets(int[] nums) {        result = new LinkedList<>();        cur = new LinkedList<>();        visited = new boolean[nums.length];        for (int i = 1; i <= nums.length; i++) {            DFS(nums, i, 0);        }        result.add(new ArrayList<>());        return result;    }    public static void main(String[] args) {        Solution solution = new Solution();        int[] nums = new int[]{1, 2, 3};        List<List<Integer>> list = solution.subsets(nums);        System.out.println(list);    }}
原创粉丝点击