39. 组合总和,40.组合总和II,131.分割回文串

39. 组合总和

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

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

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

示例 1:

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

示例 2:

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

示例 3:

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

提示:

  • 1 <= candidates.length <= 30
  • 2 <= candidates[i] <= 40
  • candidates 的所有元素 互不相同
  • 1 <= target <= 40

 之前做过三数之和、四数之和,可惜这题元素数量是不定的,只好用回溯暴力解了:

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    int sum = 0;

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

    private void backTracking(int[] candidates, int target, int index) {
        if (sum == target) {
            res.add(new ArrayList<>(path));
            return;
        }
        for(int i = index; i < candidates.length; i++) {
            sum += candidates[i];
            if(sum > target) {
                sum -= candidates[i];
                break;
            }
            path.add(candidates[i]);
            backTracking(candidates, target, i);
            sum -= candidates[i];
            path.remove(path.size() - 1);
        }
    }
}

和之前回溯题不同的是,candidates中同一个数字可以无限制重复被抽取,所以i不用+1。另外剪枝,因为candidates已经事先排序好了,所以在sum大于target时,可以直接结束循环,因为继续循环下去sum只会更大。

40. 组合总和 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]
]

示例 2:

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

提示:

  • 1 <= candidates.length <= 100
  • 1 <= candidates[i] <= 50
  • 1 <= target <= 30

 这题看似只要在上题里加一个去重就可以了,但实际没有那么简单。candidates中每个数字在每个组合中只能使用一次,但不代表candidates中的数字不能重复,把有重复元素的组合删除并不能解决问题,组合里是能出现重复元素的,只是重复次数不能超过candidates中的数量。那么每次选完数字后移,该数字就不会再被选到,这样就可以了吗?也不行,因为解集不能包含重复的组合,如果有类似candidates = [1,1], target = 1这样的输入,[1]会重复两次!那么最后用set或者map去重?超时了!

如果我们把解的集合抽象为多叉树,我们会发现实际上纵向遍历是可以重复的,对应的是在candidates中一一取数。而横向遍历是不允许重复的,重复代表又用了一遍已经用过的数。这时候我们可以利用一个和candidates等大的布尔数组used来标记数字的使用情况,true代表路径中已有这个数,false代表路径中没有这个数。当used[i - 1] == true时,说明是同一树枝candidates[i - 1]使用过,即使candidates[i] == candidates[i - 1],这样的重复也是被允许的。而当used[i - 1] == false时,说明是同一树层candidates[i - 1]使用过,此时candidates[i] == candidates[i - 1],遍历下去就会和之前的树枝重复了,要跳过:

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    boolean[] used;
    int sum = 0;

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        used = new boolean[candidates.length];
        Arrays.fill(used,false);
        backTracking(candidates, target, 0);
        return res;
    }

    private void backTracking(int[] candidates, int target, int index) {
        if (sum == target) {
            res.add(new ArrayList<>(path));
            return;
        }
        for(int i = index; i < candidates.length; i++) {
            sum += candidates[i];
            if(sum > target) {
                sum -= candidates[i];
                break;
            }
            if (i > 0 && candidates[i] == candidates[i - 1] && !used[i - 1]) {
                sum -= candidates[i];
                continue;
            }
            used[i] = true;
            path.add(candidates[i]);
            backTracking(candidates, target, i + 1);
            sum -= candidates[i];
            used[i] = false;
            path.remove(path.size() - 1);
        }
    }
}

不用used标记,直接限定i大于index也可以,这代表横向遍历时没取前面的数:

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    int sum = 0;

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        backTracking(candidates, target, 0);
        return res;
    }

    private void backTracking(int[] candidates, int target, int index) {
        if (sum == target) {
            res.add(new ArrayList<>(path));
            return;
        }
        for(int i = index; i < candidates.length; i++) {
            sum += candidates[i];
            if(sum > target) {
                sum -= candidates[i];
                break;
            }
            if (i > index && candidates[i] == candidates[i - 1]) {
                sum -= candidates[i];
                continue;
            }
            path.add(candidates[i]);
            backTracking(candidates, target, i + 1);
            sum -= candidates[i];
            path.remove(path.size() - 1);
        }
    }
}

131. 分割回文串

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

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

示例 1:

输入:s = "aab"
输出:[["a","a","b"],["aa","b"]]

示例 2:

输入:s = "a"
输出:[["a"]]

提示:

  • 1 <= s.length <= 16
  • s 仅由小写英文字母组成

 这道题难的是如何将其抽象为一个组合问题。例如对于字符串abcdef:  

  • 组合问题:选取一个a之后,在bcdef中再去选取第二个,选取b之后在cdef中在选组第三个.....。
  • 切割问题:切割一个a之后,在bcdef中再去切割第二段,切割b之后在cdef中在切割第三段.....。

所以切割问题,也能抽象为一个多叉树结构进行回溯:

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

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

    private void backTracking(String s, int startIndex) {
        // 如果起始位置大于s的大小,说明找到了一组分割方案
        if (startIndex >= s.length()) {
            res.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;
    }
}

切割出的子串,就是[startIndex, i],切割完子串后,处理剩余子串。每次处理剩余子串,都要判断想要切割的子串是否是回文(双指针),如不是则跳过,继续移动i,如是,切割子串,递归处理剩余子串。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值