leetcode473. Matchsticks to Square

題目要求

Remember the story of Little Match Girl? By now, you know exactly what matchsticks the little match girl has, please find out a way you can make one square by using up all those matchsticks. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.

Your input will be several matchsticks the girl has, represented with their stick length. Your output will either be true or false, to represent whether you could make one square using all the matchsticks the little match girl has.

Example 1:

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

Explanation: You can form a square with length 2, one side of the square came two sticks with length 1.

Example 2:

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

Explanation: You cannot find a way to form a square with all the matchsticks.

Note:

  1. The length sum of the given matchsticks is in the range of 0 to 10^9.
  2. The length of the given matchstick array will not exceed 15.

現有一個整數數組代表一堆各種長度的火柴。問這些火柴拼拼湊湊是否能夠拼成一個正方形。要求每根火柴只能使用一次。

思路和代碼

這裏採用的是深度優先遍歷的思路,即嘗試將木棍分別放在每個邊上,看看是否能夠最終構成一個正方形。一個簡單的優化方式是減少重複長度的火柴的分配。

    public boolean makesquare(int[] nums) {
        if (nums == null || nums.length == 0){
            return false;
        }
        int sum = 0;
        int max = 0;
        for (int num : nums) {
            sum += num;
            max = Math.max(num, max);
        }
        if (sum % 4 != 0) {
            return false;
        }
        int sideLength = sum / 4;
        if (max > sideLength) {
            return false;
        }
        return makesquare(nums, 0, sideLength, sideLength, sideLength, sideLength);
    }

    public boolean makesquare(int[] nums, int index, int firstSide, int secondSide, int thirdSide, int fourthSide) {
        if (index >= nums.length) return true;
        boolean canMake = false;
        if (firstSide >= nums[index]) {
            firstSide -= nums[index];
            canMake = makesquare(nums, index+1, firstSide, secondSide, thirdSide, fourthSide);
            firstSide += nums[index];
        }

        if (!canMake && secondSide != firstSide && secondSide >= nums[index]) {
            secondSide -= nums[index];
            canMake = makesquare(nums, index+1, firstSide, secondSide, thirdSide, fourthSide);
            secondSide += nums[index];
        }

        if (!canMake && thirdSide != secondSide && thirdSide >= nums[index]) {
            thirdSide -= nums[index];
            canMake = makesquare(nums, index+1, firstSide, secondSide, thirdSide, fourthSide);
            thirdSide += nums[index];
        }

        if (!canMake && fourthSide != thirdSide && fourthSide >= nums[index]) {
            fourthSide -= nums[index];
            canMake = makesquare(nums, index+1, firstSide, secondSide, thirdSide, fourthSide);
            fourthSide += nums[index];
        }
        return canMake;

    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章