(算法题)Day-20230317

分割回文串

难点:

  • 切割问题 可以抽象为组合问题
  • 如何模拟那些切割线
  • 切割问题中递归如何终止
  • 在递归循环中如何截取子串
  • 如何判断回文
package day.d0317;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @author hdbing
 * @create 2023-03-17 13:58
 */
public class T01 {
   public static void main(String[] args) {
      Solution solution = new Solution();
      List<List<String>> res = solution.partition("aab");
      System.out.println(res);
   }
}

class Solution {
   List<List<String>> lists = new ArrayList<>();
   Deque<String> deque = new LinkedList<>();

   public List<List<String>> partition(String s) {
      backTracking(s, 0);
      return lists;
   }

   private void backTracking(String s, int startIndex) {
      //如果起始位置大于s的大小,说明找到了一组分割方案
      if (startIndex >= s.length()) {
         lists.add(new ArrayList(deque));
         return;
      }
      for (int i = startIndex; i < s.length(); i++) {
         //如果是回文子串,则记录
         if (isPalindrome(s, startIndex, i)) {
            String str = s.substring(startIndex, i + 1);
            deque.addLast(str);
         } else {
            continue;
         }
         //起始位置后移,保证不重复
         backTracking(s, i + 1);
         deque.removeLast();
      }
   }
   //判断是否是回文串
   private boolean isPalindrome(String s, int startIndex, int end) {
      for (int i = startIndex, j = end; i < j; i++, j--) {
         if (s.charAt(i) != s.charAt(j)) {
            return false;
         }
      }
      return true;
   }
}

复原 IP 地址

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

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.Stack;

public class Solution {

    public List<String> restoreIpAddresses(String s) {
        int len = s.length();
        List<String> res = new ArrayList<>();
        // 如果长度不够,不搜索
        if (len < 4 || len > 12) {
            return res;
        }

        Deque<String> path = new ArrayDeque<>(4);
        int splitTimes = 0;
        dfs(s, len, splitTimes, 0, path, res);
        return res;
    }

    /**
     * 判断 s 的子区间 [left, right] 是否能够成为一个 ip 段
     * 判断的同时顺便把类型转了
     *
     * @param s
     * @param left
     * @param right
     * @return
     */
    private int judgeIfIpSegment(String s, int left, int right) {
        int len = right - left + 1;

        // 大于 1 位的时候,不能以 0 开头
        if (len > 1 && s.charAt(left) == '0') {
            return -1;
        }

        // 转成 int 类型
        int res = 0;
        for (int i = left; i <= right; i++) {
            res = res * 10 + s.charAt(i) - '0';
        }

        if (res > 255) {
            return -1;
        }
        return res;
    }

    private void dfs(String s, int len, int split, int begin, Deque<String> path, List<String> res) {
        if (begin == len) {
            if (split == 4) {
                res.add(String.join(".", path));
            }
            return;
        }

        // 看到剩下的不够了,就退出(剪枝),len - begin 表示剩余的还未分割的字符串的位数
        if (len - begin < (4 - split) || len - begin > 3 * (4 - split)) {
            return;
        }

        for (int i = 0; i < 3; i++) {
            if (begin + i >= len) {
                break;
            }

            int ipSegment = judgeIfIpSegment(s, begin, begin + i);
            if (ipSegment != -1) {
                // 在判断是 ip 段的情况下,才去做截取
                path.addLast(ipSegment + "");
                dfs(s, len, split + 1, begin + i + 1, path, res);
                path.removeLast();
            }
        }
    }
}

子集

class Solution {
    List<List<Integer>> result = new ArrayList<>();// 存放符合条件结果的集合
    LinkedList<Integer> path = new LinkedList<>();// 用来存放符合条件结果
    public List<List<Integer>> subsets(int[] nums) {
        subsetsHelper(nums, 0);
        return result;
    }

    private void subsetsHelper(int[] nums, int startIndex){
        result.add(new ArrayList<>(path));//「遍历这个树的时候,把所有节点都记录下来,就是要求的子集集合」。
        if (startIndex >= nums.length){ //终止条件可不加
            return;
        }
        for (int i = startIndex; i < nums.length; i++){
            path.add(nums[i]);
            subsetsHelper(nums, i + 1);
            path.removeLast();
        }
    }
}

子集II

注意去重 还是需要同一层上没有使用过

class Solution {
   List<List<Integer>> result = new ArrayList<>();// 存放符合条件结果的集合
   LinkedList<Integer> path = new LinkedList<>();// 用来存放符合条件结果
   boolean[] used;
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        if (nums.length == 0){
            result.add(path);
            return result;
        }
        Arrays.sort(nums);
        used = new boolean[nums.length];
        subsetsWithDupHelper(nums, 0);
        return result;
    }
    
    private void subsetsWithDupHelper(int[] nums, int startIndex){
        result.add(new ArrayList<>(path));
        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;
            }
            path.add(nums[i]);
            used[i] = true;
            subsetsWithDupHelper(nums, i + 1);
            path.removeLast();
            used[i] = false;
        }
    }
}

递增子序列

注意本题不能 先对数组进行排序,排序后那么将全是递增子序列,比如对于数组[4,7,6,7]

对于used变量,在每一层进入时都会重置,所以回溯时不再需要重置!

package day.d0317;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hdbing
 * @create 2023-03-17 15:18
 */
public class T02 {
   public static void main(String[] args) {
      Solution1 solution1 = new Solution1();
      System.out.println(solution1.findSubsequences(new int[]{4, 6, 7, 6}));
   }
}

class Solution1 {
   private List<Integer> path = new ArrayList<>();
   private List<List<Integer>> res = new ArrayList<>();

   public List<List<Integer>> findSubsequences(int[] nums) {
      backtracking(nums, 0);
      return res;
   }

   private void backtracking(int[] nums, int start) {
      if (path.size() > 1) {
         res.add(new ArrayList<>(path));
      }

      int[] used = new int[201];	// 重置
      for (int i = start; i < nums.length; i++) {
         if (!path.isEmpty() && nums[i] < path.get(path.size() - 1) || (used[nums[i] + 100] == 1))
            continue;

         used[nums[i] + 100] = 1;
         path.add(nums[i]);
         backtracking(nums, i + 1);
         path.remove(path.size() - 1);
      }
   }
}

全排列

class Solution {

    List<List<Integer>> result = new ArrayList<>();// 存放符合条件结果的集合
    LinkedList<Integer> path = new LinkedList<>();// 用来存放符合条件结果
    boolean[] used;
    public List<List<Integer>> permute(int[] nums) {
        if (nums.length == 0){
            return result;
        }
        used = new boolean[nums.length];
        permuteHelper(nums);
        return result;
    }

    private void permuteHelper(int[] nums){
        if (path.size() == nums.length){
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; i++){
            if (used[i]){
                continue;
            }
            used[i] = true;
            path.add(nums[i]);
            permuteHelper(nums);
            path.removeLast();
            used[i] = false;
        }
    }
}

全排列 II

class Solution {
    //存放结果
    List<List<Integer>> result = new ArrayList<>();
    //暂存结果
    List<Integer> path = new ArrayList<>();

    public List<List<Integer>> permuteUnique(int[] nums) {
        boolean[] used = new boolean[nums.length];
        Arrays.fill(used, false);
        Arrays.sort(nums);
        backTrack(nums, used);
        return result;
    }

    private void backTrack(int[] nums, boolean[] used) {
        if (path.size() == nums.length) {
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            // used[i - 1] == true,说明同⼀树⽀nums[i - 1]使⽤过
            // used[i - 1] == false,说明同⼀树层nums[i - 1]使⽤过
            // 如果同⼀树层nums[i - 1]使⽤过则直接跳过
            if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false) {
                continue;
            }
            //如果同⼀树⽀nums[i]没使⽤过开始处理
            if (used[i] == false) {
                used[i] = true;//标记同⼀树⽀nums[i]使⽤过,防止同一树枝重复使用
                path.add(nums[i]);
                backTrack(nums, used);
                path.remove(path.size() - 1);//回溯,说明同⼀树层nums[i]使⽤过,防止下一树层重复
                used[i] = false;//回溯
            }
        }
    }
}
posted @ 2023-03-17 22:17  黄一洋  阅读(16)  评论(0)    收藏  举报