leetcode刷题(回溯算法)

回溯法抽象为树形结构后,其遍历过程就是:for循环横向遍历,递归纵向遍历,回溯不断调整结果集。

  1. 组合

给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 k 个数的组合。

你可以按 任何顺序 返回答案。

示例 1:
输入:n = 4, k = 2
输出: [ [2,4], [3,4], [2,3], [1,2], [1,3],
[1,4], ]

# python
class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        res = []
        path = []
        def back_tracking(n, k, start_idx):
            if len(path) == k:
                return res.append(path[:])
            # 如果for循环起始位置之后的元素个数不足我们需要的元素个数,结束搜索
            # n=4,k=3, 目前已选取元素为0(path.size为0),n - (k - 0) + 1 即 4 - ( 3 - 0) + 1 = 2。
			# 从2开始搜索都是合理的,可以是组合[2, 3, 4]。
            for i in range(start_idx, n - (k - len(path)) + 2): # 剪枝优化的地方
                path.append(i)                                  # 处理节点,第一次把1加进去res = [1]
                back_tracking(n, k, i + 1)                      # 递归, 从i
                path.pop()                                      # 回溯
        back_tracking(n, k, 1)
        return res
// Java
class Solution {
    List<List<Integer>> res = new ArrayList<>();
    // List<Integer> path = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();
    public List<List<Integer>> combine(int n, int k) {
        backTracking(n, k, 1);
        return res;
    }
    private void backTracking(int n, int k, int startIndex) {
        if (path.size() == k) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = startIndex; i <= (n - (k - path.size()) + 1); i++) {
            path.add(i);
            backTracking(n, k, i + 1);
            // path.remove(path.size() - 1);
            path.removeLast();
        }
    }
}
  1. 组合总和III

找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。

示例 1:
输入: k = 3, n = 7
输出: [[1,2,4]]

# python
class Solution:
    def __init__(self):
        self.res = []
        self.path = []
        self.sum = 0
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        self.back_tracking(k, n, 1)
        return self.res
    def back_tracking(self, k, n, start_idx):
        if self.sum > n:    # 剪枝操作
            return
        if len(self.path) == k:
            if self.sum == n:
                self.res.append(self.path[:])   # 如果path.size() == k 但sum != targetSum 直接返回
            return
        for i in range(start_idx, 9 - (k - len(self.path)) + 2):
            self.path.append(i)     # 处理
            self.sum += i           # 处理
            self.back_tracking(k, n, i + 1)     # 注意i+1调整startIndex
            self.sum -= i           # 回溯
            self.path.pop()         # 回溯
        return
// Java
class Solution {
    List<List<Integer>> res = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();
    int sum = 0;
    public List<List<Integer>> combinationSum3(int k, int n) {
        backTracking(k, n, 1);
        return res;
    }
    private void backTracking(int k, int n, int startIndex) {
        if (sum > n) return;
        if (path.size() == k) {
            if (sum == n) res.add(new ArrayList(path));
            return;
        }
        for (int i = startIndex; i <= 9 - (k - path.size()) + 1; i++) {
            path.add(i);
            sum += i;
            backTracking(k, n, i + 1);
            sum -= i;
            path.removeLast();
        }
        return;
    }
}
  1. 电话号码的字母组合

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
在这里插入图片描述

示例 1:
输入:digits = “23”
输出:[“ad”,“ae”,“af”,“bd”,“be”,“bf”,“cd”,“ce”,“cf”]

# python
# 写法一
class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        res = []
        dict = ['','','abc','def','ghi','jkl','mno','pqrs','tuv','wxyz']
        if not digits:
            return res
        def backtracking(digits, start_index, path):
            if len(path) == len(digits):
                res.append(path)
                return
            row = dict[int(digits[start_index])]
            # 取出第一个数字对应的字符串,横向遍历
            for i in row:
                path += i
                # 纵向遍历过程中,只能取后一位数字对应的字符串
                backtracking(digits, start_index + 1, path)
                path = path[:-1]
        backtracking(digits, 0, '')
        return res
# 写法二
class Solution:
    def __init__(self):
        self.answers = []
        self.answer = ''
        self.letter_map = {
            '2': 'abc',
            '3': 'def',
            '4': 'ghi',
            '5': 'jkl',
            '6': 'mno',
            '7': 'pqrs',
            '8': 'tuv',
            '9': 'wxyz'
        }
    def letterCombinations(self, digits: str) -> List[str]:
        if not digits:
            return []
        self.back_tracking(digits, 0)
        return self.answers
    def back_tracking(self, digits, idx):
        if len(digits) == idx:      # 当遍历穷尽后的下一层时
            self.answers.append(self.answer)
            return
        # 单层递归逻辑
        num_string = self.letter_map[digits[idx]]
        for i in num_string:
            self.answer += i
            self.back_tracking(digits, idx + 1)
            self.answer = self.answer[:-1]
// Java
class Solution {
    List<String> answers = new ArrayList<>();
    // 每次迭代获取一个字符串,所以会设计大量的字符串拼接,所以这里选择更为高效的 StringBuild
    StringBuilder answer = new StringBuilder();
    // 初始对应所有的数字,为了直接对应2-9,新增了两个无效的字符串""
    String[] lettermap = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    public List<String> letterCombinations(String digits) {
        if (digits == null || digits.length() == 0) {
            return answers;
        }
        backTracking(digits, 0);
        return answers;
    }
    // 比如digits如果为"23", index 为0,则numString表示2对应的 abc
    private void backTracking(String digits, int index) {
        if (digits.length() == index) {
            answers.add(answer.toString());
            return;
        }
        String numString = lettermap[digits.charAt(index) - '0'];   // 这里digits是字符串形式,-'0'才能得到对应的int值
        for (int i = 0; i < numString.length(); i++) {
            answer.append(numString.charAt(i));
            backTracking(digits, index + 1);
            answer.deleteCharAt(answer.length() - 1);
        }
    }
}
  1. 组合总和

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。

candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。

示例 1:
输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释: 2 和 3可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。 7 也是一个候选, 7 = 7 。 仅有这两种组合。

# python
# 写法一
class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        candidates.sort()
        path = []
        res = []
        def backtracking(candidates, target, start_index, sum):
            if sum == target:
                res.append(path[:])
                return
            # 横向遍历,先从数组中随意取出一个数
            for i in range(start_index, len(candidates)):
                if sum + candidates[i] > target:
                    return
                path.append(candidates[i])
                sum += candidates[i] 
                # 纵向遍历,从当前元素开始取,因为可以重复
                backtracking(candidates, target, i, sum)
                sum -= candidates[i]
                path.pop()
        backtracking(candidates, target, 0, 0)
        return res
# 写法二
class Solution:
    def __init__(self):
        self.res = []
        self.path = []
        self.sum = 0
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        # 为了剪枝需要提前进行排序
        candidates.sort()
        self.back_tracking(candidates, target, 0)
        return self.res
    def back_tracking(self, candidates, target, index):
        if self.sum == target:
            return self.res.append(self.path[:])    # 因为是shallow copy,所以不能直接传入self.path
        # 如果本层 sum + condidates[i] > target,就提前结束遍历,剪枝
        for i in range(index, len(candidates)):
            if self.sum + candidates[i] > target:
                return
            self.sum += candidates[i]
            self.path.append(candidates[i])
            self.back_tracking(candidates, target, i)   # 因为无限制重复选取,所以不是i+1
            self.path.pop()
            self.sum -= candidates[i]
        
// Java
class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
            // 先进行排序
            Arrays.sort(candidates);
            List<List<Integer>> res = new ArrayList<>();
            backTracking(res, new ArrayList<>(), candidates, target, 0, 0);
            return res;
    }
    private void backTracking(List<List<Integer>> res, List<Integer> path, int[] candidates, int target, int index, int sum) {
        // 找到了数字和为 target 的组合
        if (sum == target) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            // 如果 sum + candidates[i] > target 就终止遍历
            if (sum + candidates[i] > target) {
                return;
            }
            path.add(candidates[i]);
            backTracking(res, path, candidates, target, i, sum + candidates[i]);
            path.remove(path.size() - 1);   // 回溯,移除路径 path 最后一个元素
        }
    }
}
  1. 组合总和II

给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用一次。

注意:解集不能包含重复的组合。

示例 1:
输入: candidates = [10,1,2,7,6,1,5], target = 8,
输出: [ [1,1,6], [1,2,5],
[1,7], [2,6] ]

# python
class Solution:
    def __init__(self):
        self.res = []
        self.path = []
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        candidates.sort()
        self.back_tracking(candidates, target, 0, 0)
        return self.res
    def back_tracking(self, candidates, target, sum, index):
        if sum == target:
            return self.res.append(self.path[:])
        for i in range(index, len(candidates)):
            if sum + candidates[i] > target:     # 剪枝,同39.组合总和
                return
            # 跳过同一树层使用过的元素
            if i > index and candidates[i] == candidates[i - 1]:
                continue
            sum += candidates[i]
            self.path.append(candidates[i])
            self.back_tracking(candidates, target, sum, i + 1)  # i+1跳过同一树层使用过的元素
            self.path.pop()
            sum -= candidates[i]
// Java
class Solution {
    List<List<Integer>> res = new ArrayList<>();
    Deque<Integer> path = new LinkedList<>();
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        backTracking(candidates, target, 0, 0);
        return res;
    }
    private void backTracking(int[] candidates, int target, int sum, int index) {
        if (sum == target) {
            res.add(new ArrayList(path));
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            if (sum + candidates[i] > target) return;
            if (i > index && candidates[i] == candidates[i - 1]) {
                continue;
            }
            sum += candidates[i];
            path.push(candidates[i]);
            backTracking(candidates, target, sum, i + 1);
            path.pop();
            sum -= candidates[i];
        }
    }
}
  1. 分割回文串

给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。

回文串 是正着读和反着读都一样的字符串。

示例 1:
输入:s = “aab”
输出:[[“a”,“a”,“b”],[“aa”,“b”]]

# python
class Solution:
    def __init__(self):
        self.res = []
        self.path = []
    def partition(self, s: str) -> List[List[str]]:
        self.back_tracking(s, 0)
        return self.res
    def back_tracking(self, s, index):
        if index >= len(s):
            self.res.append(self.path[:])
            return
        # 单层递归逻辑
        for i in range(index, len(s)):
            # 此次比其他组合题目多了一步判断:
            # 判断被截取的这一段子串([start_index, i])是否为回文串
            if self.is_palindrome(s, index, i):
                self.path.append(s[index : i+1])
                self.back_tracking(s, i + 1)    # 递归纵向遍历:从下一处进行切割,判断其余是否仍为回文串
                self.path.pop()
            else:
                continue
    def is_palindrome(self, s, i, j):
        while(i < j):
            if s[i] != s[j]:
                return False
            i += 1
            j -= 1
        return True
// Java
class Solution {
    List<List<String>> res = new ArrayList<>();
    Deque<String> path = new LinkedList<>();
    public List<List<String>> partition(String s) {
        backTracking(s, 0);
        return res;
    }
    private void backTracking(String s, int index) {
        if (index >= s.length()) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = index; i < s.length(); i++) {
            if (isPalindrome(s, index, i)) {
                path.addLast(s.substring(index, i + 1));
                backTracking(s, i + 1);
                path.removeLast();
            } else {
                continue;
            }
        }
    }
    private boolean isPalindrome(String s, int start, int end) {
        for (int i = start, j = end; i < j; i++, j--) {
            if (s.charAt(i) != s.charAt(j)) {
                return false;
            } 
        }
        return true;
    }
}
  1. 复原IP地址

有效 IP 地址 正好由四个整数(每个整数位于 0 到 255 之间组成,且不能含有前导 0),整数之间用 ‘.’ 分隔。

例如:“0.1.2.201” 和 “192.168.1.1” 是 有效 IP 地址,但是 “0.011.255.245”、“192.168.1.312” 和 “192.168@1.1” 是 无效 IP 地址。
给定一个只包含数字的字符串 s ,用以表示一个 IP 地址,返回所有可能的有效 IP 地址,这些地址可以通过在 s 中插入 ‘.’ 来形成。你不能重新排序或删除 s 中的任何数字。你可以按 任何 顺序返回答案。

示例 1:
输入:s = “25525511135”
输出:[“255.255.11.135”,“255.255.111.35”]

s 仅由数字组成

# python
class Solution:
    def __init__(self):
        self.res = []
    def restoreIpAddresses(self, s: str) -> List[str]:
        '''
        本质切割问题使用回溯搜索法,本题只能切割三次,所以纵向递归总共四层
        因为不能重复分割,所以需要start_index来记录下一层递归分割的起始位置
        添加变量point_num来记录逗号的数量[0,3]
        '''
        if len(s) > 12: return []
        self.back_tracking(s, 0, 0)
        return self.res
    def back_tracking(self, s, start_index, point_num):
        if point_num == 3:
            if self.is_valid(s, start_index, len(s) - 1):
                self.res.append(s[:])
                return
         # 单层递归逻辑
        for i in range(start_index, len(s) - 1):
            # [start_index, i]就是被截取的子串
            if self.is_valid(s, start_index, i):
                s = s[:i+1] + '.' + s[i+1:]
                # point_num += 1  # 在递归函数参数里+1实现回溯
                self.back_tracking(s, i + 2, point_num + 1)    # 在填入.后,下一子串起始后移2位
                # point_num -= 1              
                s = s[:i+1] + s[i+2:]
            else:
                break
    def is_valid(self, s, start, end):
        if start > end:
            return False
        # 若数字是0开头,不合法
        if s[start] == '0' and start != end:
            return False
        if not 0 <= int(s[start:end + 1]) <= 255:
            return False
        return True
// Java
class Solution {
    List<String> res = new ArrayList<>();
    public List<String> restoreIpAddresses(String s) {
        if (s.length() > 12) return res;
        backTracking(s, 0, 0);
        return res;
    }
    // startIndex: 搜索的起始位置, pointNum:添加逗点的数量
    private void backTracking(String s, int startIndex, int pointNum) {
        if (pointNum == 3) {
            // 判断第四段⼦字符串是否合法,如果合法就放进result中
            if (isValid(s, startIndex, s.length() - 1)) {
                res.add(s);
                return;
            }
        }
        for (int i = startIndex; i < s.length(); i++) {
            if (isValid(s, startIndex, i)) {
                s = s.substring(0, i + 1) + '.' + s.substring(i + 1);
                pointNum++;
                backTracking(s, i + 2, pointNum);
                pointNum--;
                s = s.substring(0, i + 1) + s.substring(i + 2);
            } else {
                break;
            }
        } 
    }
    private boolean isValid(String s, int start, int end) {
        if (start > end) return false;
        if (s.charAt(start) == '0' && start != end) return false;
        int num = Integer.parseInt(s.substring(start,end + 1)); // 如果str中含有部分非数字元素(除’-’),则会抛出错误
        if (!(0 <= num && num <= 255)) {
            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;
    }
}
  1. 子集

给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。

示例 1:
输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

# python
# 写法一
class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        path = []
        res = []
        def backtracking(nums, start_index):   
            res.append(path[:])		# 每取一个元素构成不同集合都往结果集上加,不用判断
            # if start_index >= len(nums):
            #     return
            for i in range(start_index, len(nums)):
                path.append(nums[i])
                backtracking(nums, i + 1)
                path.pop()
        backtracking(nums, 0)
        return res
# 写法二
class Solution:
    def __init__(self):
        self.res = []
        self.path = []
    def subsets(self, nums: List[int]) -> List[List[int]]:
        self.back_tracking(nums, 0)
        return self.res
    def back_tracking(self, nums, start_index):
         # 收集子集,要先于终止判断。否则for循环最后添加的nums[i]没有加进结果集
        self.res.append(self.path[:])
        if start_index >= len(nums):
            return
        for i in range(start_index, len(nums)):
            self.path.append(nums[i])
            self.back_tracking(nums, i + 1)
            self.path.pop()
Java
class Solution {
    List<List<Integer>> res = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();
    public List<List<Integer>> subsets(int[] nums) {
        if (nums.length == 0) {
            return res;
        }
        backTracking(nums, 0);
        return res;
    }
    private void backTracking(int[] nums, int startIndex) {
        //「遍历这个树的时候,把所有节点都记录下来,就是要求的子集集合」。
        res.add(new ArrayList(path));
        // 终止条件可不加, for循环遍历完整棵树会自动结束
        if (startIndex >= nums.length) {
            return;
        }
        for (int i = startIndex; i < nums.length; i++) {
            path.add(nums[i]);
            backTracking(nums, i + 1);
            path.removeLast();
        }
    }
}
  1. 子集II

给你一个整数数组 nums ,其中可能包含重复元素,请你返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列。

示例 1:
输入:nums = [1,2,2]
输出:[[],[1],[1,2],[1,2,2],[2],[2,2]]

# python
# 写法一
class Solution:
    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
        path = []
        res = []
        nums.sort()
        def backtracking(nums, start_index):
            res.append(path[:])
            for i in range(start_index, len(nums)):
                if i > start_index and nums[i] == nums[i - 1]:
                    continue
                path.append(nums[i])
                backtracking(nums, i + 1)
                path.pop()
        backtracking(nums, 0)
        return res
# 写法二
class Solution:
    def __init__(self):
        self.res = []
        self.path = []
    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        self.back_tracking(nums, 0)
        return self.res
    def back_tracking(self, nums, start_index):
        self.res.append(self.path[:])
        if start_index >= len(nums):
            return
        for i in range(start_index, len(nums)):
            if i > start_index and nums[i] == nums[i - 1]:
                # 当前后元素值相同时,跳入下一个循环,去重
                continue
            self.path.append(nums[i])
            self.back_tracking(nums, i + 1)
            self.path.pop()
// Java
class Solution {
    List<List<Integer>> res = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        backTracking(nums, 0);
        return res;
    }
    private void backTracking(int[] nums, int startIndex) {
        res.add(new ArrayList<>(path));
        if (startIndex >= nums.length) return;
        for (int i = startIndex; i < nums.length; i++) {
            if (i > startIndex && nums[i] == nums[i - 1]) {
                continue;
            }
            path.add(nums[i]);
            backTracking(nums, i + 1);
            path.removeLast();
        }
    }
}
  1. 递增子序列

给你一个整数数组 nums ,找出并返回所有该数组中不同的递增子序列,递增子序列中 至少有两个元素。你可以按 任意顺序 返回答案。

数组中可能含有重复元素,如出现两个整数相等,也可以视作递增序列的一种特殊情况。

示例 1:
输入:nums = [4,6,7,7]
输出:[[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]

# python
# 写法一
class Solution:
    def findSubsequences(self, nums: List[int]) -> List[List[int]]:
        path = []
        res = []
        def backtracking(nums, start_index):
            if len(path) >= 2:
                res.append(path[:])
            used = [False] * 201
            for i in range(start_index, len(nums)):
                # if i > start_index and nums[i] == nums[i - 1]:    # 因为无序不能用前后是否相同去重
                #     continue
                if used[nums[i] + 100] == True:     # 在纵向遍历过程中,每次横向取值都要判断当前节点的取值列表是否有重复
                    continue
                if start_index > 0 and nums[i] < nums[start_index - 1]:
                    continue
                used[nums[i] + 100] = True
                path.append(nums[i])
                backtracking(nums, i + 1)
                path.pop()
        backtracking(nums, 0)
        return res
# 写法二
class Solution:
    def __init__(self):
        self.res = []
        self.path = []
    def findSubsequences(self, nums: List[int]) -> List[List[int]]:
        '''
        本题求自增子序列,所以不能改变原数组顺序
        '''
        self.back_tracking(nums, 0)
        return self.res
    def back_tracking(self, nums, start_index):
        # 收集结果,同78.子集,仍要置于终止条件之前
        if len(self.path) >= 2:
            self.res.append(self.path[:])
        # if start_index == len(nums):
        #     return

        # 单层递归逻辑
        # 深度遍历中每一层都会有一个全新的used用于记录本层元素是否重复使用
        used = [False] * 201    # 使用列表去重,题中取值范围[-100, 100]
        for i in range(start_index, len(nums)):
            # 若当前元素值小于前一个时(非递增)或者曾用过,跳入下一循环
            if (self.path and nums[i] < self.path[-1]) or used[nums[i] + 100] == True:
                continue
            used[nums[i] + 100] = True
            self.path.append(nums[i])
            self.back_tracking(nums, i + 1)
            self.path.pop() 
// Java
class Solution {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    public List<List<Integer>> findSubsequences(int[] nums) {
        backTracking(nums, 0);
        return res;
    }
    private void backTracking(int[] nums, int startIndex) {
        if (path.size() >= 2) {
            res.add(new ArrayList<>(path));
        }
        int[] used = new int[201];
        for (int i = startIndex; 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);
        }
    }
}
  1. 全排列

给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。

示例 1:
输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

# python
# 写法一
class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        path = []
        res = []
        def backtracking(nums):
            if len(path) == len(nums):
                res.append(path[:])
                return
            for i in range(len(nums)):
                if nums[i] in path:
                    continue
                path.append(nums[i])
                backtracking(nums)
                path.pop()
        backtracking(nums)
        return res
# 写法二
class Solution:
    def __init__(self):
        self.res = []
        self.path = []
    def permute(self, nums: List[int]) -> List[List[int]]:
        '''
        因为本题排列是有序的,这意味着同一层的元素可以重复使用,但同一树枝上不能重复使用
        所以处理排列问题每层都需要从头搜索,故不再使用start_index
        '''
        self.back_tracking(nums)
        return self.res
    def back_tracking(self, nums):
        if len(self.path) == len(nums):
            self.res.append(self.path[:])
        for i in range(0, len(nums)):   # 从头开始搜索
            # 若遇到self.path里已收录的元素,跳过
            if nums[i] in self.path:
                continue
            self.path.append(nums[i])
            self.back_tracking(nums)
            self.path.pop()
// Java
class Solution {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    public List<List<Integer>> permute(int[] nums) {
        backTracking(nums);
        return res;
    }
    private void backTracking(int[] nums) {
        if (path.size() == nums.length) {
            res.add(new ArrayList<>(path));
        }
        for (int i = 0; i < nums.length; i++) {
            if (path.contains(nums[i])) {
                continue;
            }
            path.add(nums[i]);
            backTracking(nums);
            path.remove(path.size() - 1);
        }
    }
}
  1. 全排列II

给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。

示例 1:
输入:nums = [1,1,2]
输出: [[1,1,2], [1,2,1], [2,1,1]]

# python
# 写法一
class Solution:
    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        path = []
        res = []
        nums.sort()
        used = [False] * len(nums)
        def backtracking(nums):
            if len(path) == len(nums):
                res.append(path[:])
                return
            for i in range(len(nums)):
                if i > 0 and nums[i] == nums[i - 1] and used[i - 1] == True:
                    continue
                if used[i] == True:
                    continue
                used[i] = True
                path.append(nums[i])
                backtracking(nums)
                path.pop()
                used[i] = False
        backtracking(nums)
        return res
# 写法二
class Solution:
    def __init__(self):
        self.res = []
        self.path = []
    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        used = [False] * len(nums)
        self.back_tracking(nums, used)
        return self.res
    def back_tracking(self, nums, used):
        if len(self.path) == len(nums):
            self.res.append(self.path.copy())
            return
        for i in range(len(nums)):
            # used[i - 1] == false,说明同⼀树层nums[i - 1]使⽤过
            # 如果同⼀树层nums[i - 1]使⽤过则直接跳过
            if i > 0 and nums[i] == nums[i - 1] and used[i - 1] == False:
                continue
            # 如果同⼀树⽀nums[i]没使⽤过开始处理
            if used[i] == False:
                used[i] = True  # 标记同⼀树⽀nums[i]使⽤过,防止同一树支重复使用
                self.path.append(nums[i])
                self.back_tracking(nums, used)
                self.path.pop()
                used[i] = False
// Java
class Solution {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    public List<List<Integer>> permuteUnique(int[] nums) {
        Arrays.sort(nums);
        boolean[] used = new boolean[nums.length];
        Arrays.fill(used, false);
        backTracking(nums, used);
        return res;
    }
    private void backTracking(int[] nums, boolean[] used) {
        if (path.size() == nums.length) {
            res.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]);
                backTracking(nums, used);
                path.remove(path.size() - 1);
                used[i] = false;
            }
        }
    }
}
  1. 重新安排行程

给你一份航线列表 tickets ,其中 tickets[i] = [fromi, toi] 表示飞机出发和降落的机场地点。请你对该行程进行重新规划排序。

所有这些机票都属于一个从 JFK(肯尼迪国际机场)出发的先生,所以该行程必须从 JFK 开始。如果存在多种有效的行程,请你按字典排序返回最小的行程组合。

例如,行程 [“JFK”, “LGA”] 与 [“JFK”, “LGB”] 相比就更小,排序更靠前。
假定所有机票至少存在一种合理的行程。且所有的机票 必须都用一次 且 只能用一次。

示例 1:
输入:tickets =
[[“MUC”,“LHR”],[“JFK”,“MUC”],[“SFO”,“SJC”],[“LHR”,“SFO”]]
输出:[“JFK”,“MUC”,“LHR”,“SFO”,“SJC”]

# python
# 写法一
class Solution:
    def findItinerary(self, tickets: List[List[str]]) -> List[str]:
        dict = {}
        for i in tickets:
            if i[0] not in dict:
                dict[i[0]] = [i[1]]
            else:
                dict[i[0]].append(i[1])
        # 只需返回一条路径,所有行程都用上且只用一次
        path = ['JFK']
        def backtracking(start_point):
            if len(path) == len(tickets) + 1:
                return True
            if start_point in dict:
                dict[start_point].sort()
            else:
                return False
            for i in dict[start_point]:
                end_point = dict[start_point].pop(0)    # 后面对dict进行了修改,得取第一个
                path.append(end_point)                  # 否则后面把用过的加到尾部,for循环又用了一遍
                # 如果把end_point放进去是最后一次,得及时跳出循环,不然最终答案不会返回,会继续删掉最后一个元素回溯
                if backtracking(end_point):
                    return True
                dict[start_point].append(end_point)
                path.pop()
        backtracking('JFK')
        return path        
# 写法二
class Solution:
    def __init__(self):
        self.path = ["JFK"]
        self.tickets_dict = defaultdict(list)   # 索引一个不存在的键时,不会引发 keyerror 异常
        '''
        tickets_dict里面的内容是这样的
         {'JFK': ['SFO', 'ATL'], 'SFO': ['ATL'], 'ATL': ['JFK', 'SFO']})
        '''
    def findItinerary(self, tickets: List[List[str]]) -> List[str]:
        for i in tickets:
            self.tickets_dict[i[0]].append(i[1])
        self.back_tracking(tickets, "JFK")
        return self.path
    def back_tracking(self, tickets, start_point):
        if len(self.path) == len(tickets) + 1:
            return True
        self.tickets_dict[start_point].sort()
        for i in self.tickets_dict[start_point]:
            # 必须及时删除,避免出现死循环
            end_point = self.tickets_dict[start_point].pop(0)
            self.path.append(end_point)
            # 只要找到一个就可以返回了
            if self.back_tracking(tickets, end_point):
                return True
            self.path.pop()
            self.tickets_dict[start_point].append(end_point)
// Java
class Solution {
    LinkedList<String> path = new LinkedList<String>();
    Map<String, LinkedList<String>> map = new HashMap<String, LinkedList<String>>();
    public List<String> findItinerary(List<List<String>> tickets) {
        path.add("JFK");
        for (List<String> t : tickets) {
            LinkedList<String> temp = new LinkedList<>();
            if (map.containsKey(t.get(0))) {
                temp = map.get(t.get(0));
                temp.add(t.get(1));
            } else {
                temp.add(t.get(1));
            }
            Collections.sort(temp);
            map.put(t.get(0),temp);
        }
        backTracking(tickets, "JFK");
        return new ArrayList<>(path);
    }
    public boolean backTracking(List<List<String>> tickets, String startPoint) {
        if (path.size() == tickets.size() + 1) {
            return true;
        }
        if (map.get(startPoint) != null) {
            for (int i = 0; i < map.get(startPoint).size(); i++) {
                String endPoint = map.get(startPoint).getFirst();
                map.get(startPoint).removeFirst();
                path.add(endPoint);
                if (backTracking(tickets, endPoint)) {
                    return true;
                };
                path.removeLast();
                map.get(startPoint).add(endPoint);
            }
        }
        return false;
    }
}
  1. N皇后

n 皇后问题 研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。

给你一个整数 n ,返回所有不同的 n 皇后问题 的解决方案。

每一种解法包含一个不同的 n 皇后问题 的棋子放置方案,该方案中 'Q''.' 分别代表了皇后和空位。

示例 1:
在这里插入图片描述
输入:n = 4
输出:[[“.Q…”,“…Q”,“Q…”,“…Q.”],[“…Q.”,“Q…”,“…Q”,“.Q…”]]
解释:如上图所示,4 皇后问题存在两个不同的解法。

# python
# 写法一
class Solution:
    def solveNQueens(self, n: int) -> List[List[str]]:
        board = [['.'] * n for _ in range(n)]
        def isValid(board, row, col):
            # 列不重复
            for i in range(row):
                if board[i][col] == "Q":
                    return False
            i = row - 1
            j = col - 1
            while i >= 0 and j >= 0: 
                if board[i][j] == "Q":
                    return False 
                i -= 1
                j -= 1
            i = row - 1
            j = col + 1
            while i >= 0 and j <= len(board) - 1: 
                if board[i][j] == "Q":
                    return False
                i -= 1
                j += 1
            return True
        res = []
        def backtracking(board, n, row):
            if row == n:
                tmp = []
                for i in board:
                    tmp.append(''.join(i))
                res.append(tmp[:])
                return
            for i in range(n):
                if isValid(board, row, i):
                    board[row][i] = "Q"
                    backtracking(board, n, row + 1)
                    board[row][i] = "."
        backtracking(board, n, 0)
        return res 
# 写法二
class Solution:
    def __init__(self):
        self.board = []
        self.res = []       # 用于存放符合n皇后问题的结果
    def solveNQueens(self, n: int) -> List[List[str]]:
        if not n:
            return []
        self.board = [['.'] * n for _ in range(n)]      # 构建n*n的棋盘
        self.back_tracking(self.board, 0, n)
        return self.res
    def isValid(self, board, row, col):
        # 判断同一列是否冲突
        for i in range(row):
            if board[i][col] == 'Q':
                return False
        # 判断左上角是否冲突
        i = row - 1
        j = col - 1
        while i>=0 and j>=0:
            if board[i][j] == 'Q':
                return False
            i -= 1
            j -= 1
        # 判断右上角是否冲突
        i = row - 1
        j = col + 1
        while i>=0 and j<len(board):
            if board[i][j] == 'Q':
                return False
            i -= 1
            j += 1
        return True
    def back_tracking(self, board, row, n):
        # 如果走到最后一行(row = 4),说明已经找到一个解
        if row == n:
            temp_res = []
            for i in board:
                temp_str = ''.join(i)
                temp_res.append(temp_str)
            self.res.append(temp_res)
        for j in range(n):
            if not self.isValid(board, row, j):
                continue
            board[row][j] = 'Q'
            self.back_tracking(board, row + 1, n)
            board[row][j] = '.'
// Java
class Solution {
    List<List<String>> res = new ArrayList<>();
    public List<List<String>> solveNQueens(int n) {
        char[][] chessboard = new char[n][n];
        for (char[] list : chessboard) {
            Arrays.fill(list, '.');
        }
        backTracking(chessboard, 0, n);
        return res;
    }
    public boolean isValid(char[][] chessboard, int row, int col) {
        for (int i = 0; i <= row; i++) {
            if (chessboard[i][col] == 'Q') {
                return false;
            }
        }
        for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
            if (chessboard[i][j] == 'Q') {
                return false;
            }
        }
        for (int i = row - 1, j = col + 1; i >= 0 && j < chessboard.length; i--, j++) {
            if (chessboard[i][j] == 'Q') {
                return false;
            }
        }
        return true;
    }
    public void backTracking(char[][] chessboard, int row, int n) {
        if (row == n) {
            List<String> temp = new ArrayList<>();
            for (char[] list : chessboard) {
                temp.add(String.copyValueOf(list));         //copyValueOf () 方法用于将字符数组的值复制到字符串中
            }
            res.add(temp);
        }
        for (int j = 0; j < n; j++) {
            if (isValid(chessboard, row, j)) {
                chessboard[row][j] = 'Q';
                backTracking(chessboard, row + 1, n);
                chessboard[row][j] = '.';
            }
        }
    }
}
  1. 解数独

编写一个程序,通过填充空格来解决数独问题。

数独的解法需 遵循如下规则

数字 1-9 在每一行只能出现一次。
数字 1-9 在每一列只能出现一次。
数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。(请参考示例图)
数独部分空格内已填入了数字,空白格用 '.' 表示。

示例:
在这里插入图片描述

输入:board = [[“5”,“3”,“.”,“.”,“7”,“.”,“.”,“.”,“.”],
[“6”,“.”,“.”,“1”,“9”,“5”,“.”,“.”,“.”],
[“.”,“9”,“8”,“.”,“.”,“.”,“.”,“6”,“.”],
[“8”,“.”,“.”,“.”,“6”,“.”,“.”,“.”,“3”],
[“4”,“.”,“.”,“8”,“.”,“3”,“.”,“.”,“1”],
[“7”,“.”,“.”,“.”,“2”,“.”,“.”,“.”,“6”],
[“.”,“6”,“.”,“.”,“.”,“.”,“2”,“8”,“.”],
[“.”,“.”,“.”,“4”,“1”,“9”,“.”,“.”,“5”],
[“.”,“.”,“.”,“.”,“8”,“.”,“.”,“7”,“9”]]
输出:[[“5”,“3”,“4”,“6”,“7”,“8”,“9”,“1”,“2”],
[“6”,“7”,“2”,“1”,“9”,“5”,“3”,“4”,“8”],
[“1”,“9”,“8”,“3”,“4”,“2”,“5”,“6”,“7”],
[“8”,“5”,“9”,“7”,“6”,“1”,“4”,“2”,“3”],
[“4”,“2”,“6”,“8”,“5”,“3”,“7”,“9”,“1”],
[“7”,“1”,“3”,“9”,“2”,“4”,“8”,“5”,“6”],
[“9”,“6”,“1”,“5”,“3”,“7”,“2”,“8”,“4”],
[“2”,“8”,“7”,“4”,“1”,“9”,“6”,“3”,“5”],
[“3”,“4”,“5”,“2”,“8”,“6”,“1”,“7”,“9”]]
解释:输入的数独如上图所示,唯一有效的解决方案如下所示:
在这里插入图片描述

# python
class Solution:
    def solveSudoku(self, board: List[List[str]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        self.back_tracking(board)
        return board
    def back_tracking(self, board):
        # 若有解,返回True;若无解,返回False
        for row in range(len(board)):   # 遍历行
            for col in range(len(board[0])):    # 遍历列
                if board[row][col] != '.':  # 若空格内已有数字,跳过
                    continue
                for i in range(1, 10):
                    if self.is_valid(row, col, i, board):
                        board[row][col] = str(i)
                        if self.back_tracking(board): return True
                        board[row][col] = '.'
                # 若数字1-9都不能成功填入空格,返回False无解
                return False
        return True # 有解
    def is_valid(self, row, col, val, board):
        # 判断同一列是否冲突
        for i in range(9):
            if board[i][col] == str(val):
                return False
        # 判断同一行是否冲突
        for j in range(9):
            if board[row][j] == str(val):
                return False
        start_row = (row // 3) * 3
        start_col = (col // 3) * 3
        # 判断同一九宫格是否有冲突
        for i in range(start_row, start_row + 3):
            for j in range(start_col, start_col + 3):
                if board[i][j] == str(val):
                    return False
        return True
// Java
class Solution {
    public void solveSudoku(char[][] board) {
        backTracking(board);
    }
    public boolean backTracking(char[][] board) {
        for (int row = 0; row < board.length; row++) {
            for (int col = 0; col < board[0].length; col++) {
                if (board[row][col] != '.') {
                    continue;
                }
                for (char i = '1'; i <= '9'; i++) {
                    if (isValid(row, col, i, board)) {
                        board[row][col] = i;
                        if (backTracking(board)) return true;
                        board[row][col] = '.';
                    }
                }
                return false;
            }
        }
        return true;
    }
    public boolean isValid(int row, int col, char val, char[][] board) {
        for (int i = 0; i < board.length; i++) {
            if (board[i][col] == val) return false;
        }
        for (int j = 0; j < board[0].length; j++) {
            if (board[row][j] == val) return false;
        }
        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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

天涯小才

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

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

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

打赏作者

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

抵扣说明:

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

余额充值