最后一块石头的重量2时间复杂度巨高解法

刚做完137周的周赛。
最后一道题如图
在这里插入图片描述
做题的时候还显示是Hard难度,现在就变成Medium了。不过这题确实不算难。以下是我的垃圾DFS解法。最坏情况下数组长度超过7个就TLE了233333

class Solution {
public:
	int lastStoneWeightII(vector<int>& stones) {
		dfs(stones);
		return res;
	}
	void dfs(vector<int> s)
	{
		if (ok)
			return;
		if (!s.size())
		{
			res = 0;
			ok = true;
			return;
		}
		if (s.size() == 1)
		{
			res = min(res, s[0]);
			return;
		}
		for (int i = 0; i < s.size() - 1; i++)
		{
			for (int j = i + 1; j < s.size(); j++)
			{
				int x = min(s[i], s[j]);
				int y = max(s[i], s[j]);
				y -= x;
				vector<int> t;
				if (s.size() != 2)
				{
					t.resize(s.size() - 2);
					for (int k = 0, l = 0; k < t.size(); k++, l++)
					{
						while (l == i || l == j)
							l++;
						t[k] = s[l];
					}
				}
				if (!y)
					dfs(t);
				else
				{
					t.push_back(y);
					dfs(t);
				}
			}
		}
	}
private:
	int res = INT_MAX;
	bool ok = false;
};

大神解法是这样的
在这里插入图片描述
写这篇是我决心在一周之内再做这道题AC它,最好是这种类型题,不该用DFS的。

发布了26 篇原创文章 · 获赞 6 · 访问量 6468

猜你喜欢

转载自blog.csdn.net/weixin_43975128/article/details/90341427