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

93. 复原 IP 地址 - 力扣(LeetCode)

class Solution {
    public List restoreIpAddresses(String s) {
        List res = new ArrayList<>();
        StringBuilder sb = new StringBuilder(s);
        backtrack(res, sb, 0, 0);
        return res;
    }

    private void backtrack(List res, StringBuilder sb, int idx, int dots) {
        if (dots == 3) {
            if (isValid(sb, idx, sb.length() - 1)) {
                res.add(sb.toString());
            }
            return;
        }

        for (int i = idx; i < sb.length(); i++) {
            if (isValid(sb, idx, i)) {
                sb.insert(i + 1, '.');
                dots += 1;
                backtrack(res, sb, i + 2, dots);
                dots -= 1;
                sb.deleteCharAt(i + 1);
            }
        }
    }

    private boolean isValid(StringBuilder sb, int start, int end) {
        if (start > end) return false;
        if (sb.charAt(start) == '0' && start != end) return false;
        int num = 0;
        for (int i = start; i <= end; i++) {
            if (sb.charAt(i) > '9' || sb.charAt(i) < '0') return false;
            int digit = sb.charAt(i) - '0';
            num = num * 10 + digit;
            if (num > 255) return false;
        }
        return true;
    }
}

78. 子集 - 力扣(LeetCode)

class Solution {
    public List> subsets(int[] nums) {
        List> res = new ArrayList<>();
        List list = new ArrayList<>();
        backtrack(res, list, nums, 0);
        return res;
    }

    private void backtrack(List> res, List list, int[] nums, int idx) {
        res.add(new ArrayList(list));

        for (int i = idx; i < nums.length; i++) {
            list.add(nums[i]);
            backtrack(res, list, nums, i + 1);
            list.remove(list.size() - 1);
        }
    }
}

90. 子集 II - 力扣(LeetCode)

class Solution {
    public List> subsetsWithDup(int[] nums) {
        List> res = new ArrayList<>();
        List list = new ArrayList<>();
        Arrays.sort(nums);
        boolean[] visited = new boolean[nums.length];
        backtrack(res, list, nums, visited, 0);
        return res;
    }

    private void backtrack(List> res, List list, int[] nums, boolean[] visited, int idx) {
        res.add(new ArrayList<>(list));

        for (int i = idx; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i - 1] && !visited[i - 1]) continue;
            list.add(nums[i]);
            visited[i] = true;
            backtrack(res, list, nums, visited, i + 1);
            list.remove(list.size() - 1);
            visited[i] = false;
        }
    }
}

你可能感兴趣的:(代码随想录三刷,算法)