Leetcode 78. Subsets

来源:互联网 发布:淘宝网汽车坐垫套途观l 编辑:程序博客网 时间:2024/06/12 13:51

题目

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

思路

思路为
起始subset集为:[]
添加S0后为:[], [S0]
添加S1后为:[], [S0], [S1], [S0, S1]
添加S2后为:[], [S0], [S1], [S0, S1], [S2], [S0, S2], [S1, S2], [S0, S1, S2]
红色subset为每次新增的。显然规律为添加Si后,新增的subset为克隆现有的所有subset,并在它们后面都加上Si。

代码

package leetcodeArray;import java.util.ArrayList;import java.util.Arrays;import java.util.Collection;import java.util.List;public class Leetcode78SubSet {    @SuppressWarnings("unchecked")    public List<List<Integer>> subsets(int[] nums) {        List<List<Integer>> result = new ArrayList<>();        result.add(new ArrayList<Integer>());        //Arrays.sort(nums);        for( int i:nums){            List<List<Integer>> tmp = new ArrayList<>();            for(List<Integer> sub:result){                    List<Integer> a = new ArrayList<>(sub);                    a.add(i);                    tmp.add(a);            }            result.addAll( tmp);        }        return result;    }    public static void main(String[] args){        int[] nums = {1, 2, 3,4};        Leetcode78SubSet test = new Leetcode78SubSet();        System.out.println(test.subsets(nums));    }}

他山之玉

public List<List<Integer>> subsets(int[] nums) {    List<List<Integer>> list = new ArrayList<>();    Arrays.sort(nums);    backtrack(list, new ArrayList<>(), nums, 0);    return list;}private void backtrack(List<List<Integer>> list , List<Integer> tempList, int [] nums, int start){    list.add(new ArrayList<>(tempList));    for(int i = start; i < nums.length; i++){        tempList.add(nums[i]);        backtrack(list, tempList, nums, i + 1);        tempList.remove(tempList.size() - 1);    }}
原创粉丝点击