代码随想录算法训练营第二十八天 | 93.复原IP地址 78.子集 90.子集II

代码随想录算法训练营第二十八天 | 93.复原IP地址 78.子集 90.子集II

一、力扣93.复原IP地址

题目链接
思路:重要的就两块,一块是确定终止条件,这里用记录下来加点的数量来判断是否到达叶节点,另一块是确定是0-255的数,其他的正常回溯。

class Solution {
    List<String> list = new ArrayList<>();
    public List<String> restoreIpAddresses(String s) {
        if (s.length() < 4 || s.length() > 12) return list;
        backTracking(s, 0, 0);
        return list;
    }
    void backTracking(String s, int startIndex, int pointNum) {
        if (pointNum == 3) {
            if (isIP(s, startIndex, s.length() - 1)) {
                list.add(s);
            }
            return;
        }
        for (int i = startIndex; i < s.length(); i++) {
            if (isIP(s, startIndex, i)) {
                s = s.substring(0, i+1) + "." + s.substring(i+1);
                pointNum++;
                backTracking(s, i+2, pointNum);
                s = s.substring(0, i+1) + s.substring(i+2);
                pointNum--;
            } else {
                return;
            }
        }
    }
    boolean isIP(String s, int start, int end) {
        if (start > end) return false;
        if (s.charAt(start) == '0' && start != end) return false;
        int num = 0;
        for (int i = start; i <= end; i++) {
            if (s.charAt(i) < '0' || s.charAt(i) > '9') return false;
            num = num * 10 + (s.charAt(i) - '0');
            if (num > 255) return false;
        }

        return true;
    }
}

二、力扣78.子集

题目链接
思路:排序后,每迭代一次就收取一次,即每个节点都收取。

class Solution {
    List<List<Integer>> arrayLists = new ArrayList<>();
    List<Integer> list = new ArrayList<>();
    public List<List<Integer>> subsets(int[] nums) {
        Arrays.sort(nums);
        backTracking(nums, 0);
        return arrayLists;
    }
    void backTracking(int[] nums, int startIndex) {
        arrayLists.add(new ArrayList<>(list));
        if (startIndex == nums.length) return;
        for (int i = startIndex; i < nums.length; i++) {
            list.add(nums[i]);
            backTracking(nums, i+1);
            list.remove(list.size()-1);
        }
    }
}

三、力扣90.子集II

题目链接
思路:纵向不去重,横向去重

class Solution {
    List<List<Integer>> arrayLists = new ArrayList<>();
    List<Integer> list = new ArrayList<>();
    boolean[] used;
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        used = new boolean[nums.length];
        Arrays.fill(used, false);
        backTracking(nums, 0);
        return arrayLists;
    }
    void backTracking(int[] nums, int startIndex) {
        arrayLists.add(new ArrayList<>(list));
        if (startIndex == nums.length) return;
        for (int i = startIndex; i < nums.length; i++) {
            if (i > 0 && nums[i]==nums[i-1] && !used[i-1]) continue;
            list.add(nums[i]);
            used[i] = true;
            backTracking(nums, i+1);
            list.remove(list.size()-1);
            used[i] = false;
        }
    }
}

你可能感兴趣的:(算法)