https://leetcode.com/problems/subsets/

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

解题 :这类问题基本思想就是dfs遍历出所以组合,这道题求的是全部组合(不同大小size)templist记录当前的组合字母,所以每次进入下一轮dfs就把templist添加到list里面。整个templist添加过程可以用下面的图来表示,就清晰多了。

          123
            []
        /    |    \
        1    2     3
       /\    |    
    12   13  23
    /
   123
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);
    }
}

results matching ""

    No results matching ""