栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

[Java算法] - n 数之和解题模板(nSum)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

[Java算法] - n 数之和解题模板(nSum)

nSum通用模板

注意:

  1. 输入数组必须使用 Arrays.sort排序!
  2. 返回List结果不包含重复值;
  3. 核心思路是以2Sum为基准,通过递归重复计算。

代码:

   
    public List> nSum(int[] nums, int target, int n, int startIndex) {
        // 返回结果
        List> res = new ArrayList>();
        // base case
        if (startIndex > nums.length - 1) {
            return res;
        }
        if (n == 2) {
            int left = startIndex, right = nums.length - 1;
            while (left < right) {
                int twoSumTarget = nums[left] + nums[right];
                // 用于消重的基准值
                int baseLeft = nums[left], baseRight = nums[right];
                if (twoSumTarget == target) {
                    List tmp = new ArrayList<>();
                    tmp.add(nums[left]);
                    tmp.add(nums[right]);
                    res.add(tmp);
                    while (left < right && nums[left] == baseLeft) left++;  // 消重
                    while (left < right && nums[right] == baseRight) right--;  // 消重
                } else if (twoSumTarget > target) {
                    right--;
                    while (left < right && nums[right] == baseRight) right--;  // 消重
                } else if (twoSumTarget < target) {
                    left++;
                    while (left < right && nums[left] == baseLeft) left++;  // 消重
                }
            }
        } else {
            // n>2的时候调用递归
            for (int i = startIndex; i < nums.length; i++) {
                List> nRes = nSum(nums, target - nums[i], n - 1, i + 1);
                for (List list : nRes) {
                    list.add(nums[i]);
                    res.add(list);
                }
                while (i < nums.length - 1 && nums[i] == nums[i + 1]) i++;  // 消重
            }
        }
        return res;
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/821936.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号