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

nSum通用模板

注意:

  1. 输入数组必须使用 Arrays.sort排序!
  2. 返回List结果不包含重复值;
  3. 核心思路是以2Sum为基准,通过递归重复计算。其中 2Sum 主要使用双指针(两端指针/左右指针)

代码:

   /**
     * @param nums: 排序后的数组
     * @param target: 目标值
     * @param n: n数之和的n
     * @param startIndex: 开始索引
     * @return  List<List<Integer>>
     */
    public List<List<Integer>> nSum(int[] nums, int target, int n, int startIndex) {
        // 返回结果
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        // 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<Integer> 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--;
                } else if (twoSumTarget < target) {
                    left++;
                }
            }
        } else {
            // n>2的时候调用递归
            for (int i = startIndex; i < nums.length; i++) {
                // 注意:这里传入的下一位是i的后一位!肯定不能包括i
                List<List<Integer>> nRes = nSum(nums, target - nums[i], n - 1, i + 1);
                for (List<Integer> list : nRes) {
                    list.add(nums[i]);
                    res.add(list);
                }
                while (i < nums.length - 1 && nums[i] == nums[i + 1]) i++;  // 消重
            }
        }
        return res;
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值