78. Subsets

Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: nums = [1,2,3]
Output:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]
第一种方法:回溯backtracking
class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> list = new ArrayList<List<Integer>>();
       Arrays.sort(nums);
        backtracking(list, new ArrayList<>(), nums, 0);
        return list;
        
    }
    public void backtracking(List<List<Integer>> list, List<Integer> templist, int[] arr, int start){
        list.add(new ArrayList<>(templist));
        for(int i = start; i < arr.length; i++){
            templist.add(arr[i]);
            backtracking(list,templist,arr,i+1);
            templist.remove(templist.size()-1);
        }
    }
}

 

posted @ 2019-09-16 23:20  Schwifty  阅读(134)  评论(0编辑  收藏  举报