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

題目要求給定一正整數數組,表示一組火柴的長度。判斷該組火柴能否拼接成正方形。火柴不能折斷但是可以拼接。首先判斷總長度是不是4的倍數。如果不是返回false。接着遍歷所有火柴,直到一邊被填滿。遞歸地對所有邊進行同樣的操作。

代碼如下:

class Solution {  
public:  
    bool makesquare(vector<int>& nums) {  
        if(nums.size() < 4)
			return false;  
        vector<int> len(4, 0);  
        int total = accumulate(nums.begin(), nums.end(), 0);  
        if(total%4) 
			return false;  
        sort(nums.begin(), nums.end(), greater<int>());  
        return chkSquare(nums, len, 0, total/4);  
    }  
private:
	bool chkSquare(const vector<int>& nums, vector<int>& len, int idx, int sdLen) {  
        if(idx == nums.size()) {  
            if(len[0] == sdLen && len[1] == sdLen && len[2] == sdLen)  
                return true;  
            else 
				return false;  
        }  
        for(int i=0; i<4; ++i) {  
            if(len[i] + nums[idx] <= sdLen) {  
                len[i] += nums[idx];  
                if(chkSquare(nums, len, idx+1, sdLen)) 
					return true;  
                len[i] -= nums[idx];  
            }  
        }  
        return false;  
    }   
};  


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