leetcode专题之回溯

69 阅读1分钟

心大事小,心小事大

  1. 但是要清楚子集问题和组合问题、分割问题的的区别,子集是收集树形结构中树的所有节点的结果而组合问题、分割问题是收集树形结构中叶子节点的结果。这就是为什么子集类问题不需要return,而其他的问题需要return

  2. 去重方式有两种:
    以子集2为例:leetcode.com/problems/su…
    第一种:通过used数组去重

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();
    public void backtracking(int[] nums, int startIndex, boolean[] used) {
        res.add(new ArrayList<>(path));

        for(int i = startIndex; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i-1] && used[i-1] == false) {
                continue;
            }
            used[i] = true;
            path.add(nums[i]);
            backtracking(nums, i + 1, used);
            path.removeLast();
            used[i] = false;
        }
    }
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        boolean[] used = new boolean[nums.length];
        Arrays.sort(nums);
        backtracking(nums, 0, used);
        return res;
    }
}

第二种:通过树层加map去重

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();

    public void backtracking(int[] nums, int startIndex) {

        res.add(new ArrayList<>(path));
        
        Map<Integer, Integer> map = new HashMap<>();
        for(int i = startIndex; i < nums.length; i++) {
            if(map.containsKey(nums[i]) && map.get(nums[i]) == 1) {
                continue;
            }
            map.put(nums[i], 1);
            path.add(nums[i]);
            backtracking(nums, i + 1);
            path.removeLast();
        }
    }
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        backtracking(nums, 0);
        return res;
    }
}

经典之回溯 + dfs 332. Reconstruct Itinerary

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();
    public void backtracking(int[] nums, int startIndex, boolean[] used) {
        res.add(new ArrayList<>(path));

        for(int i = startIndex; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i-1] && used[i-1] == false) {
                continue;
            }
            used[i] = true;
            path.add(nums[i]);
            backtracking(nums, i + 1, used);
            path.removeLast();
            used[i] = false;
        }
    }
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        boolean[] used = new boolean[nums.length];
        Arrays.sort(nums);
        backtracking(nums, 0, used);
        return res;
    }
}