將一個數組分紅四個和相等的子數組 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.ide

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.spa

Example 1:code

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:orm

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.

解決:遞歸

①  跟以前有道題Partition Equal Subset Sum有點像,那道題問咱們能不能將一個數組分紅和相等的兩個子數組,而這道題其實是讓咱們將一個數組分紅四個和相等的子數組get

先給數組從大到小的順序排序,這樣大的數字先加,若是超過target了,就直接跳過了後面的再次調用遞歸的操做。input

咱們創建一個長度爲4的數組sums來保存每一個邊的長度和,咱們但願每條邊都等於target,數組總和的四分之一。而後咱們遍歷sums中的每條邊,咱們判斷若是加上數組中的當前數字大於target,那麼咱們跳過,若是沒有,咱們就加上這個數字,而後對數組中下一個位置調用遞歸,若是返回爲真,咱們返回true,不然咱們再從sums中對應位置將這個數字減去繼續循環。it

class Solution { //39ms     public boolean makesquare(int[] nums) {         if (nums == null || nums.length < 4) return false;         int sum = 0;         for (int n : nums){             sum += n;         }         if (sum % 4 != 0) return false;         int[] sums = new int[4];         Arrays.sort(nums);         return dfs(nums,sums,nums.length - 1,sum / 4);     }     public boolean dfs(int[] nums,int[] sums,int i,int target){         if (i < 0){             return sums[0] == target && sums[1] == target && sums[2] == target;         }         for (int j = 0;j < 4;j ++){             if (sums[j] + nums[i] > target) continue;             sums[j] += nums[i];             if (dfs(nums,sums,i - 1,target)) return true;             sums[j] -= nums[i];         }         return false;     } }

相關文章
相關標籤/搜索