LeetCode Subsets

来源:互联网 发布:2011年十大网络流行语 编辑:程序博客网 时间:2024/06/05 06:18

题目:

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:

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

题意:

给定一个数组,然后按照一个数字,两个数字等情况得到所有的组合。并且将数组中的那些List中的数字按照非降序的顺序排列,注意:数组中的数字没有重复的出现。

题解:

通过观察,我们可以发现,其实还是有规律可寻的。每添加一个数字,都是在之前的解的基础上添加当前的元素,然后再多加一个当前元素,就行了,当然别忘了还有一个空集需要添加。那么我就可以每次在循环的时候,将上一次得到的List<List<Integer>>给一个临时变量,然后再对这个临时变量进行操作,并且将其添加新元素后再保存给原来的result。

public List<List<Integer>> subsets(int[] nums)     {    if (nums == null)    return null;    Arrays.sort(nums);    List<List<Integer>> result = new ArrayList<List<Integer>>();    for (int i = 0; i < nums.length; i++)     {    List<List<Integer>> temp = new ArrayList<List<Integer>>();       //get sets that are already in result    for (List<Integer> a : result)     {    temp.add(new ArrayList<Integer>(a));//注意,java里面的对象都是传引用的,而ArrayList中放的是List,所以传的也是引用,故必须要新建一个新的对象,才能更改相应的值;如果直接是temp.add(a).那么会导致result和temp都变了,因为java里对象都是传引用的(地址)    }         //add nums[i] to existing sets    for (List<Integer> a : temp)     {    a.add(nums[i]);    }         //add nums[i] only as a set    List<Integer> single = new ArrayList<Integer>();    single.add(nums[i]);    temp.add(single);         result.addAll(temp);    }    result.add(new ArrayList<Integer>());    return result;    }

0 0