carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode1995: Count Special Quadruplets #319

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

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:

Constraints:

carloscn commented 1 year ago

Analysis

pub fn count_quadruplets(nums: Vec<i32>) -> i32
{
    if nums.len() < 4 {
        return -1;
    }

    let mut ret:i32 = 0;
    let len:usize = 1 << nums.len();

    for mask in 0..len {
        // count '1' bits number
        {
            let mut count:usize = 0;
            let mut t_mask:usize = mask;
            while t_mask != 0 {
                t_mask &= t_mask - 1;
                count += 1;
            }
            if count != 4 {
                continue;
            }
        }

        // judge the numbers
        {
            let mut cv:Vec<i32> = vec![];
            for i in 0..nums.len() {
                if mask & (1 << i) != 0 {
                    cv.push(nums[i]);
                }
            }

            if cv[0] + cv[1] + cv[2] == cv[3] {
                ret += 1;
            }
        }
    }

    return ret;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1168265 https://github.com/carloscn/structstudy/commit/e3d6ee2bac96597f74c03427f1ae4815b271609e