1995. Count Special Quadruplets

Given a 0-indexed integer array nums, return the number of distinct quadruplets (a, b, c, d) such that:

  • nums[a] + nums[b] + nums[c] == nums[d], and
  • a < b < c < d

 

Example 1:

Input: nums = [1,2,3,6]
Output: 1
Explanation: The only quadruplet that satisfies the requirement is (0, 1, 2, 3) because 1 + 2 + 3 == 6.

Example 2:

Input: nums = [3,3,6,4,5]
Output: 0
Explanation: There are no such quadruplets in [3,3,6,4,5].

Example 3:

Input: nums = [1,1,1,3,5]
Output: 4
Explanation: The 4 quadruplets that satisfy the requirement are:
- (0, 1, 2, 3): 1 + 1 + 1 == 3
- (0, 1, 3, 4): 1 + 1 + 3 == 5
- (0, 2, 3, 4): 1 + 1 + 3 == 5
- (1, 2, 3, 4): 1 + 1 + 3 == 5

 

Constraints:

  • 4 <= nums.length <= 50
  • 1 <= nums[i] <= 100

1995. Count Special Quadruplets
struct Solution;

impl Solution {
    fn count_quadruplets(nums: Vec<i32>) -> i32 {
        let n = nums.len();
        let mut res = 0;
        for i in 0..n {
            for j in i + 1..n {
                for k in j + 1..n {
                    for l in k + 1..n {
                        if nums[i] + nums[j] + nums[k] == nums[l] {
                            res += 1;
                        }
                    }
                }
            }
        }
        res
    }
}

#[test]
fn test() {
    let nums = vec![1, 2, 3, 6];
    let res = 1;
    assert_eq!(Solution::count_quadruplets(nums), res);
    let nums = vec![3, 3, 6, 4, 5];
    let res = 0;
    assert_eq!(Solution::count_quadruplets(nums), res);
    let nums = vec![1, 1, 1, 3, 5];
    let res = 4;
    assert_eq!(Solution::count_quadruplets(nums), res);
}