算法:(十三)回溯法

13.1 排列

面试题79:所有子集

题目:

给定一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。

解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。

示例:

输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
public List<List<Integer>> subsets(int[] nums){
    List<List<Integer>> result = new LinkedList<>();
    if( nums.length == 0){
        return result;
    }
    helper(result, nums, new LinkedList<Integer>(), 0);
    return result;
}

private void helper(List<List<Integer>> result, int[] nums, LinkedList<Integer> subset, int index) {
    if(index == nums.length){
        result.add(new LinkedList<>(subset));
    }else{
        helper(result, nums, subset, index + 1);

        subset.add(nums[index]);
        helper(result, nums, subset, index + 1);
        subset.removeLast();
    }
}

面试题80:包含k个元素的组合

题目:

给定两个整数 nk,返回 1 ... n 中所有可能的 k 个数的组合。

示例 1:

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

public List<List<Integer>> combine(int n, int k){
    List<List<Integer>> result = new LinkedList<>();
    if(k == 0){
        return result;
    }
    helper(n, k, result, new LinkedList<Integer>(), 0);
    return result;
}

private void helper(int n, int k, List<List<Integer>> result, LinkedList<Integer> subset, int index) {
    if(subset.size() == k || index == n){
        result.add(new LinkedList<>(subset));
    } else {
        helper(n, k, result, subset, index + 1);

        subset.add(index);
        helper(n, k, result, subset, index + 1);
        subset.removeLast();
    }
}

面试题81:允许重复选择元素的组合

题目:

给定一个无重复元素的正整数数组 candidates 和一个正整数 target ,找出 candidates 中所有可以使数字和为目标数 target 的唯一组合。

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

对于给定的输入,保证和为 target 的唯一组合数少于 150 个。

示例 1:

输入: candidates = [2,3,6,7], target = 7
输出: [[7],[2,2,3]]
示例 2:

输入: candidates = [2,3,5], target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]

public List<List<Integer>> combinationSum(int[] nums, int target){
    List<List<Integer>> result = new LinkedList<>();
    if(nums.length == 0){
        return result;
    }
    helper(result, nums, new LinkedList<Integer>(), target, 0);
    return result;
}

private void helper(List<List<Integer>> result, int[] nums, LinkedList<Integer> subset, int target, int index) {
    if(target == 0){
        result.add(new LinkedList<>(subset));
    } else if(target > 0){
        helper(result, nums, subset, target, index + 1);

        subset.add(nums[index]);
        helper(result, nums, subset, target - nums[index], index + 1);
        subset.removeLast();
    }
}

面试题82:包含重复元素集合的组合

题目:

给定一个可能有重复数字的整数数组 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]
]
示例 2:

输入: candidates = [2,5,2,1,2], target = 5,
输出:
[
[1,2,2],
[5]
]

public List<List<Integer>> combinationSum(int[] nums, int target){
    Arrays.sort(nums);
    List<List<Integer>> result = new LinkedList<>();
    if(nums.length == 0){
        return result;
    }
    helper(nums, result, new LinkedList<Integer>(), 0, target);
    return result;
}

private void helper(int[] nums, List<List<Integer>> result, LinkedList<Integer> subset, int index, int target) {
    if(target == 0){
        result.add(new LinkedList<>(subset));
    } else if(index < nums.length){
        helper(nums, result, subset, getNext(nums, index + 1), target);

        subset.add(nums[index]);
        helper(nums, result, subset, index, target);
        subset.removeLast();
    }
}

private int getNext(int[] nums, int index) {
    while(index < nums.length - 1 && nums[index] == nums[index + 1]){
        index++;
    }
    return index;
}

13.2 排列

面试题83:没有重复元素集合的全排列

题目:

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

示例:

输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
public List<List<Integer>> permute(int[] nums) {
    List<List<Integer>> result = new LinkedList<>();
    if(nums.length == 0){
        return result;
    }
    helper(result, 0, nums);
    return result;
}

private void helper(List<List<Integer>> result, int step, int[] nums) {
    if(step == nums.length){
        List<Integer> permutation = new LinkedList<>();
        for (int num : nums) {
            permutation.add(num);
        }
        result.add(permutation);
    } else {
        for(int j = step; j < nums.length; j++){
            swap(step, j, nums);
            helper(result, step + 1, nums);
            swap(j, step, nums);
        }
    }
}

private void swap(int j, int step, int[] nums) {
    int temp = nums[step];
    nums[step] = nums[j];
    nums[j] = temp;
}

面试题84:包含重复元素集合的全排列

题目:给定一个可包含重复数字的整数集合 nums按任意顺序 返回它所有不重复的全排列。

示例:

输入:nums = [1,1,2]
输出:
[[1,1,2],
 [1,2,1],
 [2,1,1]]
public List<List<Integer>> permuteUnique(int[] nums){
    List<List<Integer>> result = new LinkedList<>();
    if(nums.length == 0){
        return result;
    }
    helper(nums, result, 0);
    return result;
}

private void helper(int[] nums, List<List<Integer>> result, int step) {
    if(step == nums.length){
        List<Integer> permutation = new LinkedList<>();
        for (int num : nums) {
            permutation.add(num);
        }
        result.add(permutation);
    } else {
        HashSet<Integer> set = new HashSet<>();
        for(int j = step; j < nums.length; j++){
            if(!set.contains(nums[j])){
                set.add(nums[j]);

                swap(nums, j, step);
                helper(nums, result, step + 1);
                swap(nums, j, step);
            }
        }
    }
}
private void swap(int[] nums, int j, int step) {
    int temp = nums[step];
    nums[step] = nums[j];
    nums[j] = temp;

}

13.3 使用回溯法解决其他问题

面试题85:生成匹配的括号

题目:

正整数 n 代表生成括号的对数,请设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。

示例:

输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]
public List<String> generateParenthesis(int n){
    List<String> result = new LinkedList<>();
    if(n == 0){
        return result;
    }
    helper(n, n, "", result);
    return result;
}

private void helper(int left, int right, String parenthesis, List<String> result) {
    if(left == 0 && right == 0){
        result.add(parenthesis);
        return;
    }
    if(left > 0){
        helper(left - 1, right, parenthesis + "(", result);
    }
    if(right > left){
        helper(left, right - 1, parenthesis + ")", result);
    }
}

面试题86:分割回文子字符串

题目:

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

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

示例:

输入:s = “google”
输出:[[“g”,“o”,“o”,“g”,“l”,“e”],[“g”,“oo”,“g”,“l”,“e”],[“goog”,“l”,“e”]]

public String[][] partition(String s){
    List<List<String>> temp = new ArrayList<>();
    helper(temp, s, 0, new ArrayList<>());

    String[][] result = new String[temp.size()][];
    for (int i = 0; i < temp.size(); i++) {
        result[i] = new String[temp.get(i).size()];
        for (int j = 0; j < temp.get(i).size(); j++) {
            result[i][j] = temp.get(i).get(j);
        }
    }
    return result;
}

private void helper(List<List<String>> result, String s, int start, ArrayList<String> subset) {
    if(start == s.length()){
        result.add(new ArrayList<>(subset));
    }

    for(int i = start; i < s.length(); i++){
        if(isPalindrome(s, start, i)){
            subset.add(s.substring(start, i + 1));
            // 从当前分割的位置之后开始继续分割
            helper(result, s, i + 1, subset);
            // 去掉当前分割的方案,继续探索下一个方案
            subset.remove(subset.size() - 1);
        }
    }
}

private boolean isPalindrome(String s, int start, int end) {
    while(start < end){
        if(s.charAt(start++) != s.charAt(end--)){
            return false;
        }
    }
    return true;
}

面试题87:恢复IP地址

题目:

给定一个只包含数字的字符串 s ,用以表示一个 IP 地址,返回所有可能从 s 获得的 有效 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 地址。

示例 1:

输入:s = "010010"
输出:["0.10.0.10","0.100.1.0"]

示例 2:

输入:s = "10203040"
输出:["10.20.30.40","102.0.30.40","10.203.0.40"]
public List<String> restoreIpAddresses(String s){
    List<String> result = new ArrayList<>();
    helper(0, 0, "", "", s, result);
    return result;
}

private void helper(int i, int segI, String seg, String ip, String s, List<String> result) {
    if(i == s.length() && segI == 3 && isValid(seg)){
        result.add(ip + seg);
    } else if(i < s.length() && segI <= 3) {
        char ch = s.charAt(i);
        if(isValid(seg + ch)){
            helper(i + 1, segI, seg + ch, ip, s, result);
        }
        if(seg.length() > 0 && segI < 3){
            helper(i + 1, segI + 1, "" + ch, ip + seg + '.', s, result);
        }
    }
}

private boolean isValid(String seg) {
    return Integer.parseInt(seg) <= 255 && (seg.equals("0") || seg.charAt(0) != '0');
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值