leetcode 473. Matchsticks to Square 一个经典的深度优先遍历DFS的应用

来源:互联网 发布:迅雷 mac为什么没图标 编辑:程序博客网 时间:2024/06/05 22:43

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:
The length sum of the given matchsticks is in the range of 0 to 10^9.
The length of the given matchstick array will not exceed 15.

这道题最直接的方法就是DFS深度优先遍历,又涨姿势了,这道题很值得学习

需要注意的是,这道题需要剪枝,对原数组做逆序排序不会超时,否者会超时

代码如下:

#include <iostream>#include <vector>#include <map>#include <set>#include <queue>#include <stack>#include <string>#include <climits>#include <algorithm>#include <sstream>#include <functional>#include <bitset>#include <cmath>using namespace std;bool cmp(int a, int b){    return a >= b;}class Solution{public:    bool makesquare(vector<int>& nums)     {        if (nums.size() <= 3)            return false;        long long sum = 0;        for (int a : nums)            sum += a;        if (sum % 4 != 0)            return false;        sort(nums.begin(),nums.end(),cmp);        vector<int> edge(4, 0);        return dfs(nums, edge, 0, sum / 4);    }    bool dfs(vector<int>& nums, vector<int>& edge, int index, int target)    {        if (index == nums.size())        {            for (int i = 0; i < edge.size(); i++)            {                if (edge[i] != target)                    return false;            }            return true;        }        else        {            for (int i = 0; i < 4; i++)            {                if (edge[i] + nums[index] > target)                    continue;                edge[i] += nums[index];                if (dfs(nums, edge, index + 1, target))                    return true;                edge[i] -= nums[index];            }            return false;        }    }};