leetcode刷题-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.

Input: nums = [1,2,3]
Output:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]

求所有子集,要求求出所有结果大部分情况是用dfs进行搜索。参数中需要注意的是通过startIndex控制向前搜索,然后回溯法求解

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> results = new ArrayList<>();
        // 边界处理
        if (nums == null) {
            return results;
        }
        dfs(nums, 0, new ArrayList<>(), results);
        return results;
    }
    
    private void dfs(int [] nums, int startIndex, List<Integer> subset, List<List<Integer>> results) {
    	//deepcopy subset to results
        results.add(new ArrayList<>(subset));
        //dfs 回溯求subsets
        for (int i = startIndex; i < nums.length; i++) {
            subset.add(nums[i]);
            dfs(nums, i + 1, subset, results);
            subset.remove(subset.size() - 1);
        }
    }
}

90.Subsets II

Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
Input: [1,2,2]
Output:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]

Subsets II和Subsets的区别是输入中可以存在重复元素,1和第一个2 ,1和第二个2是相同的,选择一个。所以要在Subsets 的基础上进行选代表操作,不能跳过第一个2选择第二个2,要添加的操作是如果后一个数等于前一个数且没有选择前一个数择跳过,对应代码为

if (i != 0 && nums[i] == nums[i - 1] && i > startIndex) {
                continue;
            }
class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> results = new ArrayList<>();
        if (nums == null) {
            return results;
        }
        Arrays.sort(nums);
        dfs(nums, 0, new ArrayList<Integer>(), results);
        
        return results;
    }
    
    private void dfs(int [] nums, int startIndex, List<Integer> subset, List<List<Integer>> results) {
        results.add(new ArrayList<>(subset));
        
        for (int i = startIndex; i < nums.length; i++) {
        	//如果当前数和前一位相同且没有选前一位 continue
            if (i != 0 && nums[i] == nums[i - 1] && i > startIndex) {
                continue;
            }
            subset.add(nums[i]);
            dfs(nums, i + 1, subset, results);
            subset.remove(subset.size() - 1);
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章