[473] C language LeetCode brush. Fight square matches (M)

Remember the fairy tale "The Little Match Girl" it? Now that you know how many little girls have a match, please find a match can be used for all makes up a square method. Can not break matches, the matches can be connected, and each match should be used.

Girl has input the number of matches, each match indicated by the length thereof. Output that is if you can use all the matches spell square.

Example 1:

Input: [1,1,2,2,2]
Output: true

Explanation: energy makes up a square side length of 2, two on each side matches.
Example 2:

Input: [3,3,3,3,4]
Output: false

Explanation: You can not spell a square with all the matches.

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/matchsticks-to-square
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

Array consider ordering. Then dfs, first with the big matches, save some time. Find exit conditions, four sides are equal to the target, target = sum / 4.

bucket [4] is the length of the four sides, a match selection plus the length, selected not remember to subtract the newly added.

int comp(void const *a, void const *b) {
    return *(int *)b - *(int *)a;
}

bool generate(int i, int *nums, int target, int *bucket, int numsSize) {
    int j;

    if (i >= numsSize) {
        return (bucket[0] == target) && (bucket[1] == target) &&
                (bucket[2] == target) && (bucket[3] == target);
    }

    for (j = 0; j < 4; j++) {
        if (bucket[j] + nums[i] > target) {
            continue;
        }
        bucket[j] += nums[i];
        if (generate(i+1, nums, target, bucket, numsSize)) {
            return true;
        }

        bucket[j] -= nums[i];
    }

    return false;
}

bool makesquare(int* nums, int numsSize){
    int flag = 0;
    int bucket[4] = {0};
    int i;
    int sum = 0;

    if (numsSize < 4) {
        return false;
    }

    for (i = 0; i < numsSize; i++) {
        sum += nums[i];
    }

    if (sum % 4) {
        return false;
    }

    qsort(nums, numsSize, sizeof(int), comp);

    return generate(0, nums, sum/4, bucket, numsSize);
}

 

Published 149 original articles · won praise 17 · views 110 000 +

Guess you like

Origin blog.csdn.net/jin615567975/article/details/104416669