Matchsticks to Square

https://www.lintcode.com/problem/matchsticks-to-square/description

import java.util.Arrays;

public class Solution {
    /**
     * @param nums: an array
     * @return: whether you could make one square using all the matchsticks the little match girl
     * has
     */
    public boolean makesquare(int[] nums) {
        // Write your code here
        if (nums.length == 0) {
            return false;
        }
        Arrays.sort(nums);
        int sum = Arrays.stream(nums).sum();
        if (sum % 4 != 0) {
            return false;
        }
        sum /= 4;
        if (nums[nums.length - 1] > sum) {
            return false;
        }
        boolean[] visited = new boolean[nums.length];
        return serach(nums, visited, 4, 0, 0, sum);
    }

    private boolean serach(int[] nums, boolean[] visited, int count, int index, int tempSum, int
            sum) {
        if (count == 1) {
            return true;
        }
        if (tempSum == sum) {
            return serach(nums, visited, count - 1, 0, 0, sum);
        }
        for (int i = index; i < nums.length; i++) {
            int num = nums[i];
            if (visited[i]) {
                continue;
            }
            if (tempSum + num <= sum) {
                visited[i] = true;
                boolean serach = serach(nums, visited, count, index + 1, tempSum + num, sum);
                if (serach) {
                    return true;
                } else {
                    visited[i] = false;
                }
            } else {
                break;
            }
        }
        return false;
    }
}

你可能感兴趣的:(Matchsticks to Square)