回溯-[18] 四数之和

/*
 * @lc app=leetcode.cn id=18 lang=java
 *
 * [18] 四数之和
 */

// InetgerCharacterllengthremoveAtInetgerCharacter@lc code=start
class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
      List<List<Integer>> re = new ArrayList<>();

      // 先排序
      Arrays.sort(nums);
      
      // target : 目标值
      // 4 : 处理4次
      // nums : 采样数组
      // 0 : 开始下标
      // re : 结果变量
      // new ArrayList<>(4) : 零时变量可以确定只存储4个元素  
      calFourSum(target, 4, nums, 0, re, new ArrayList<>(4));

      return re;
    }


    private void calFourSum(int target, int times, int[] nums, int index, List<List<Integer>> re, List<Integer> sub){
      if(times == 0){
          // 当已经获取4个数检查是否满足和为target
          if(target == 0)
            re.add(new ArrayList<>(sub));
        return;
      }else if(times > nums.length - index){
        // 当可获取个数少于times直接返回
        return;
      }

      for(int i = index; i < nums.length;){
        // 加入当前节点
        sub.add(nums[i]);
        calFourSum(target - nums[i], times - 1, nums, i + 1, re, sub);
        // 移除当前节点
        sub.remove(sub.size() - 1);
        
        // 设置下一个i对应的值不同于当前i对应的值
        if(i + 1 < nums.length && nums[i] == nums[i + 1]){
          int ts = 2;
          while(ts + i < nums.length && nums[ts + i] == nums[i]){
            ts++;
          }
          i += ts;
        }else{
          i++;
        }
      }

      return;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值