力扣中级组合类题目解答全分析(77. 组合 40. 组合总和 II 216. 组合总和 III 39. 组合总和 377. 组合总和 Ⅳ )

力扣中级组合类题目解答全分析

题目一描述:77. 组合 https://leetcode.cn/problems/combinations/

给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 k 个数的组合。你可以按任何序返回答案。

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

拿到这道题当时第一反应便是暴力求解,然而k重for循环不会写。所以便断了思路,事后才知道其实就是一道全排列问题罢了,本科期间就一直害怕dfs 动态规划啥的,现在尝试着做了几道题,发现其实也还是挺有趣蛮有意思的。
重点:把握状态变量以及终止条件
那么这道题,我们需要什么?首先,我们需要一个数组记录当前节点是否已经被使用,因为我们的结果里面是不含重复数值的,也就是说每一个数值我们只能使用一次。然后我们需要一个depth变量来记录当前遍历的层数,因为我们只需要k个数,所以我们遍历的层数到达k层即可终止。最后,我们需要一个Stack栈来存储已选节点列表。(注意:此处的used数组其实也可以不需要。因为我们设置了遍历开始的index在上一次遍历的后一位,那么也可以避免重复值的出现。)

class Solution {
        public List<List<Integer>> combine(int n, int k) {
            List<List<Integer>> res = new ArrayList<>();
            int[] nums = new int[n];
            for (int i = 0; i < n; i++) {
                nums[i] = i + 1;
            }
            if (nums.length == 0) {
                return res;
            }
            Deque<Integer> path = new ArrayDeque<Integer>();
            boolean used[] = new boolean[nums.length];
            dfs(path, used, nums, 0, res, k, 0);
            return res;
        }


        private void dfs(Deque<Integer> path, boolean[] used, int[] nums, int depth, List<List<Integer>> res, int length, int begin) {
            if (depth == length) {
                res.add(new ArrayList<>(path));
                return;
            }
            for (int i = begin; i < nums.length; i++) {
                if (used[i]) {
                    continue;
                }
                path.addLast(nums[i]);
                used[i] = true;
                dfs(path, used, nums, depth + 1, res, length, i + 1);
                path.removeLast();
                used[i] = false;
            }
        }
    }

dfs核心代码无非两部分,递归结束条件以及遍历列表持续递归。在递归前记得改变相应状态值,在递归结束之后记得还原即可。

题目二描述: 40. 组合总和 II https://leetcode.cn/problems/combination-sum-ii/

给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用 一次 。
注意:解集不能包含重复的组合。

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

这一题与上一题的不同之处在哪?是不是变成了个数不限但是所选数字的总和固定了,同类转换思想,是不是我们也可以将这道题转换成全排列问题?反正只要结果之和等于我们的目标值便是一组符合要求的答案。但是那样做复杂度过高,肯定会超时,那么我们重新寻找状态变量,我们抓住当前位置之和即可,上一题抓住的是遍历深度。这题还要额外注意的便是给定的数字中会有重复的数值,那么我们进行预处理,对给定数组排序,每次从不同值开始dfs即可解决重复答案问题(对应代码中的while循环),然后限制一下遍历开始的index即可。

class Solution {
        public List<List<Integer>> combinationSum2(int[] candidates, int target) {
            int len = candidates.length;
            List<List<Integer>> res = new ArrayList<>();
            if (len == 0) {
                return res;
            }
            Deque<Integer> path = new ArrayDeque<Integer>();
            Arrays.sort(candidates);
            dfs(res, target, 0, path, len, candidates, 0);
            return res;

        }

        private void dfs(List<List<Integer>> res, int target, int currentSum, Deque<Integer> path, int length, int[] candidates, int startIndex) {

            if (currentSum == target) {
                res.add(new ArrayList<>(path));
                return;
            }

            for (int i = startIndex; i < length; i++) {
                if (currentSum + candidates[i] <= target) {
                    path.addLast(candidates[i]);
                    dfs(res, target, currentSum + candidates[i], path, length, candidates, i + 1);
                    path.removeLast();
                }

                while (i <= length - 2 && candidates[i] == candidates[i + 1]) {
                    i++;
                }
            }
        }
    }

题目三描述:216. 组合总和 III https://leetcode.cn/problems/combination-sum-iii/

找出所有相加之和为 n 的 k 个数的组合,且满足下列条件:
只使用数字1到9
每个数字 最多使用一次
返回 所有可能的有效组合的列表 。该列表不能包含相同的组合两次,组合可以以任何顺序返回。

输入: k = 3, n = 9
输出: [[1,2,6], [1,3,5], [2,3,4]]
解释:
1 + 2 + 6 = 9
1 + 3 + 5 = 9
2 + 3 + 4 = 9

此题与上面两题不同的便是,个数固定并且总和也固定,那么我们同时把握这两个状态即可。

class Solution {
        public List<List<Integer>> combinationSum3(int k, int n) {
            int[] nums = new int[9];
            for (int i = 0; i < 9; i++) {
                nums[i] = i + 1;
            }
            List<List<Integer>> res = new ArrayList<>();
            Deque<Integer> path = new ArrayDeque<Integer>();

            dfs(nums, path, res, 0, n, 0, k, 0);
            return res;

        }

        private void dfs(int[] nums, Deque<Integer> path, List<List<Integer>> res, int currentSum, int target, int startIndex, int k, int depth) {

            if(depth == k && currentSum == target) {
                res.add(new ArrayList<>(path));
                return;
            }

            if (depth > k) {
                return;
            }

            for (int i = startIndex; i < nums.length; i++) {
                if(currentSum + nums[i] <= target) {
                    path.addLast(nums[i]);
                    dfs(nums, path, res, currentSum + nums[i], target, i + 1, k, depth + 1);
                    path.removeLast();
                }

            }

        }
    }

题目四描述:39. 组合总和 https://leetcode.cn/problems/combination-sum/

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target 的不同组合数少于 150 个。

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

此题关键在于无重复数据,但是每个数字可以被重复使用,所以我们得在startIndex上下文章,前面题目都是上一次的i+1,我们这则是i。

class Solution {
        public List<List<Integer>> combinationSum(int[] candidates, int target) {
            int len = candidates.length;
            List<List<Integer>> res = new ArrayList<>();
            if (len == 0) {
                return res;
            }
            Arrays.sort(candidates);
            Deque<Integer> path = new ArrayDeque<Integer>();
            dfs(res, target, 0, path, len, candidates, 0);
            return res;

        }

        private void dfs(List<List<Integer>> res, int target, int currentSum, Deque<Integer> path, int length, int[] candidates, int startIndex) {

            if (currentSum == target) {
                res.add(new ArrayList<>(path));
                return;
            }

            for (int i = startIndex; i < length; i++) {
                if (currentSum + candidates[i] <= target) {
                    path.addLast(candidates[i]);
                    dfs(res, target, currentSum + candidates[i], path, length, candidates, i);
                    path.removeLast();
                }


            }

        }
    }

题目五描述:377. 组合总和 Ⅳ https://leetcode.cn/problems/combination-sum-iv/

给你一个由 不同 整数组成的数组 nums ,和一个目标整数 target 。请你从 nums 中找出并返回总和为 target 的元素组合的个数。
题目数据保证答案符合 32 位整数范围。

输入:nums = [1,2,3], target = 4
输出:7
解释:
所有可能的组合为:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
请注意,顺序不同的序列被视作不同的组合。

这道题就很有意思了,如果说我们用全排列的思想用dfs,每次遍历都从0开始,这样结果肯定是没啥问题的,但是时间时间复杂度扛不住,肯定会超时,感兴趣的可以自己试试,我当时试了一下。然后这题只需要得到最终的总数,所以用回溯很好做,我们只要记录每个到每个位置有多少种组合方法,那么接下来就和跳楼梯一样,看从哪些位置可以一步走到当前我的位置,那么那些位置的总数之和便是当前我的位置的解法总数。

class Solution {
        Map<Integer, Integer> map = new HashMap<>();
        public int combinationSum4(int[] nums, int target) {
            return backTrack(nums, target);
        }

        private int backTrack(int[] nums, int remains) {
            if (remains == 0) {
                return 1;
            }

            if (map.containsKey(remains)) {
                return map.get(remains);
            }

            int res = 0;
            for (int i = 0; i < nums.length; i++) {
                if (remains >= nums[i]) {
                    res += backTrack(nums, remains - nums[i]);
                }
            }
            map.put(remains, res);
            return res;

        }


    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值