回溯专项练习LeetCode

77. 组合

image-20221013112323864

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

        void dfs(int n, int k, int index) {
            if (path.size() == k) {
                result.add(new ArrayList<>(path));
                return;
            }
            for (int i = index; i <= n - (k - path.size()) + 1; i++) {
                path.add(i);
                dfs(n, k, i + 1);
                path.removeLast();
            }
        }

        public List<List<Integer>> combine(int n, int k) {
            dfs(n, k, 1);
            return result;
        }
    }

216. 组合总和 III

image-20221013135119900

class Solution {
        boolean[] vis = new boolean[100];
        List<List<Integer>> ans = new ArrayList<>();
        LinkedList<Integer> path = new LinkedList<>();

        void dfs(int k, int n , int index) {
            if (path.size() > k || n < 0) {
                return;
            }
            if (n == 0 && path.size() == k) {
                ans.add(new ArrayList<>(path));
                return;
            }
            for (int i = index; i < 10; i++) {
                if(vis[i] == false){
                    vis[i] = true;
                    path.add(i);
                    dfs(k,n-i,i+1);
                    path.removeLast();
                    vis[i] = false;
                }
            }
        }

        public List<List<Integer>> combinationSum3(int k, int n) {
            dfs(k, n,1);
            return ans;
        }
    }

17. 电话号码的字母组合

image-20221013141335763

class Solution {
        List<String> ans = new ArrayList<>();
        String[] numString = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        StringBuffer now = new StringBuffer();

        void dfs(String s, int index) {
            if (index == s.length()) {
                ans.add(now.toString());
                return;
            }
            for (int i = 0; i < numString[s.charAt(index) - '0'].length(); i++) {
                now.append(numString[s.charAt(index) - '0'].charAt(i));
                dfs(s, index + 1);
                now.deleteCharAt(now.length() - 1);
            }
        }

        public List<String> letterCombinations(String digits) {
            if (digits == null || digits.length() == 0) {
                return new ArrayList<>();
            }
            dfs(digits, 0);
            return ans;
        }
    }

39. 组合总和

image-20221014085657715

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

        void dfs(int[] nums, int target, int index) {
            if (target < 0) {
                return;
            }
            if (target == 0) {
                ans.add(new ArrayList<>(path));
                return;
            }
            for (int i = index; i < nums.length; i++) {
                path.add(nums[i]);
                dfs(nums, target - nums[i], i);
                path.remove(path.size() - 1);
            }
        }

        public List<List<Integer>> combinationSum(int[] candidates, int target) {
            Arrays.sort(candidates);
            dfs(candidates, target, 0);
            return ans;
        }
    }

40. 组合总和 II

image-20221014093002239

class Solution {
        Set<List<Integer>> ans = new HashSet<>();
        List<Integer> path = new ArrayList<>();

        void dfs(int[] nums, int target, int index) {
            if (target < 0) {
                return;
            }
            if (target == 0) {
                ans.add(new ArrayList<>(path));
                return;
            }
            for (int i = index; i < nums.length; i++) {
                if (i > index && nums[i] == nums[i - 1]) {
                    continue;
                }
                path.add(nums[i]);
                dfs(nums, target - nums[i], i + 1);
                path.remove(path.size() - 1);
            }
        }

        public List<List<Integer>> combinationSum2(int[] candidates, int target) {
            Arrays.sort(candidates);
            dfs(candidates, target, 0);
            List<List<Integer>> l = new ArrayList<>(ans);
            return l;
        }
    }

131. 分割回文串

image-20221014094203106

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

        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;
        }

        void dfs(String s, int index) {
            if (index >= s.length()) {
                lists.add(new ArrayList<>(deque));
                return;
            }
            for (int i = index; i < s.length(); i++) {
                if(isPalindrome(s,index,i)){
                    String ss = s.substring(index,i+1);
                    deque.addLast(ss);
                }else{
                    continue;
                }
                dfs(s,i+1);
                deque.removeLast();
            }
        }

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

93. 复原 IP 地址

image-20221014095952042

class Solution {
        List<String> ans = new ArrayList<>();

        void dfs(String s, int index, int sum) {
            if (sum == 3 && isValid(s,index,s.length()-1)) {
                ans.add(s);
                return;
            }
            for (int i = index; i < s.length(); i++) {
                if (isValid(s, index, i)) {
                    s = s.substring(0, i + 1) + "." + s.substring(i + 1);    //在str的后⾯插⼊⼀个逗点
                    sum++;
                    dfs(s, i + 2, sum);// 插⼊逗点之后下⼀个⼦串的起始位置为i+2
                    sum--;// 回溯
                    s = s.substring(0, i + 1) + s.substring(i + 2);// 回溯删掉逗点
                } else {
                    break;
                }
            }
        }

        public List<String> restoreIpAddresses(String s) {
            dfs(s, 0, 0);
            return ans;
        }

        Boolean isValid(String s, int start, int end) {
            if (start > end) {
                return false;
            }
            if (s.charAt(start) == '0' && start != end) { // 0开头的数字不合法
                return false;
            }
            int num = 0;
            for (int i = start; i <= end; i++) {
                if (s.charAt(i) > '9' || s.charAt(i) < '0') { // 遇到⾮数字字符不合法
                    return false;
                }
                num = num * 10 + (s.charAt(i) - '0');
                if (num > 255) { // 如果⼤于255了不合法
                    return false;
                }
            }
            return true;
        }
    }

78. 子集

image-20221014100816736

class Solution {
        List<List<Integer>> ans = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        void dfs(int[] nums,int index){
            ans.add(new ArrayList<>(path));
            for(int i = index; i < nums.length;i++){

                path.add(nums[i]);
                dfs(nums,i+1);
                path.remove(path.size()-1);
            }
        }
        public List<List<Integer>> subsets(int[] nums) {
            dfs(nums,0);
            return ans;
        }
    }

90. 子集 II

image-20221015084349746

class Solution {
        Set<List<Integer>> ans = new HashSet<>();
        List<Integer> path = new ArrayList<>();

        void dfs(int[] nums, int index) {
            ans.add(new ArrayList<>(path));
            for (int i = index; i < nums.length; i++) {
                path.add(nums[i]);
                dfs(nums, i + 1);
                path.remove(path.size() - 1);
            }
        }

        public List<List<Integer>> subsetsWithDup(int[] nums) {
            Arrays.sort(nums);
            dfs(nums, 0);
            return new ArrayList<>(ans);
        }
    }

491. 递增子序列

image-20221015092704553

class Solution {
        Set<List<Integer>> ans = new HashSet<>();
        List<Integer> path = new ArrayList<>();

        void dfs(int[] nums, int index) {
            if (path.size() >= 2) {
                ans.add(new ArrayList<>(path));
            }
            int[] used = new int[201];
            for (int i = index; i < nums.length; i++) {
                boolean bl = !path.isEmpty() && nums[i] < path.get(path.size() -1 ) || (used[nums[i]+100] == 1);
                if(bl){
                    continue;
                }
                used[nums[i] + 100] = 1;
                path.add(nums[i]);
                dfs(nums, i + 1 );
                path.remove(path.size() - 1);
            }
        }

        public List<List<Integer>> findSubsequences(int[] nums) {
            dfs(nums,0);
            return new ArrayList<>(ans);
        }
    }

46. 全排列

image-20221015094153560

class Solution {
        List<List<Integer>> ans = new ArrayList<>();

        void dfs(int[] nums, LinkedList<Integer>path) {
            if (path.size() == nums.length) {
                ans.add(new ArrayList<>(path));
            }
            for (int i = 0; i < nums.length; i++) {
                if(path.contains(nums[i])){
                    continue;
                }
                path.add(nums[i]);
                dfs(nums, path);
                path.removeLast();
            }
        }

        public List<List<Integer>> permute(int[] nums) {
            if(nums.length == 0){
                return ans;
            }
            dfs(nums,new LinkedList<>());
            return ans;
        }
    }

47. 全排列 II

image-20221015095429382

class Solution {
        Set<List<Integer>> ans = new HashSet<>();
        int[] map = new int[100];
        void dfs(int[] nums, LinkedList<Integer> path) {
            if (path.size() == nums.length) {
                ans.add(new ArrayList<>(path));
            }
            for (int i = 0; i < nums.length; i++) {
                if(map[i] != 0){
                    continue;
                }
                path.add(nums[i]);
                map[i] = 1;
                dfs(nums,path);
                map[i] = 0;
                path.removeLast();
            }
        }

        public List<List<Integer>> permuteUnique(int[] nums) {
            dfs(nums, new LinkedList<>());
            return new ArrayList<>(ans);
        }
    }

332. 重新安排行程

image-20221015101842644

用的非回溯 深搜拆边 逆序输出

class Solution {
        Map<String, PriorityQueue<String>> map = new HashMap<>();
        LinkedList<String> ans = new LinkedList<>();

        void dfs(String s) {
            while(map.containsKey(s) && map.get(s).size() > 0){
                String ss = map.get(s).poll();
                dfs(ss);
            }
            ans.add(s);
        }

        public List<String> findItinerary(List<List<String>> tickets) {
            for (int i = 0; i < tickets.size(); i++) {
                String from = tickets.get(i).get(0),
                        to = tickets.get(i).get(1);
                if(!map.containsKey(from)){
                    map.put(from,new PriorityQueue<>());
                }
                map.get(from).offer(to);
            }
            dfs("JFK");
            Collections.reverse(ans);
            return new ArrayList<>(ans);
        }
    }

51. N 皇后

image-20221015103918274

class Solution {
        List<List<String>> res = new ArrayList<>();

        public List<List<String>> solveNQueens(int n) {
            char[][] chessboard = new char[n][n];
            for (char[] c : chessboard) {
                Arrays.fill(c, '.');
            }
            backTrack(n, 0, chessboard);
            return res;
        }


        public void backTrack(int n, int row, char[][] chessboard) {
            if (row == n) {
                res.add(Array2List(chessboard));
                return;
            }

            for (int col = 0; col < n; ++col) {
                if (isValid(row, col, n, chessboard)) {
                    chessboard[row][col] = 'Q';
                    backTrack(n, row + 1, chessboard);
                    chessboard[row][col] = '.';
                }
            }

        }


        public List Array2List(char[][] chessboard) {
            List<String> list = new ArrayList<>();

            for (char[] c : chessboard) {
                list.add(String.copyValueOf(c));
            }
            return list;
        }


        public boolean isValid(int row, int col, int n, char[][] chessboard) {
            // 检查列
            for (int i = 0; i < row; ++i) { // 相当于剪枝
                if (chessboard[i][col] == 'Q') {
                    return false;
                }
            }

            // 检查45度对角线
            for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
                if (chessboard[i][j] == 'Q') {
                    return false;
                }
            }

            // 检查135度对角线
            for (int i = row - 1, j = col + 1; i >= 0 && j <= n - 1; i--, j++) {
                if (chessboard[i][j] == 'Q') {
                    return false;
                }
            }
            return true;
        }
    }

37. 解数独
image-20221015104354666

class Solution {
        public void solveSudoku(char[][] board) {
            solveSudokuHelper(board);
        }

        private boolean solveSudokuHelper(char[][] board) {
            for (int i = 0; i < 9; i++) {
                for (int j = 0; j < 9; j++) {
                    if (board[i][j] != '.') {
                        continue;
                    }
                    // (i, j) 这个位置放k是否合适
                    for (char k = '1'; k <= '9'; k++) {
                        if (isValidSudoku(i, j, k, board)) {
                            board[i][j] = k;
                            if (solveSudokuHelper(board)) {
                                return true;
                            }
                            board[i][j] = '.';
                        }
                    }
                    return false;
                }
            }
            return true;
        }

        private boolean isValidSudoku(int row, int col, char val, char[][] board) {
            // 同行是否重复
            for (int i = 0; i < 9; i++) {
                if (board[row][i] == val) {
                    return false;
                }
            }
            // 同列是否重复
            for (int j = 0; j < 9; j++) {
                if (board[j][col] == val) {
                    return false;
                }
            }
            // 9宫格里是否重复
            int startRow = (row / 3) * 3;
            int startCol = (col / 3) * 3;
            for (int i = startRow; i < startRow + 3; i++) {
                for (int j = startCol; j < startCol + 3; j++) {
                    if (board[i][j] == val) {
                        return false;
                    }
                }
            }
            return true;
        }
    }

回溯完结

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

楠风丶北枝

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值