OJ刷题------[算法课分支限界法]Partition to K Equal Sum Subsets(划分k个相等的子集)

题目:

Given an integer array nums and an integer k, return true if it is possible to divide this array into k non-empty subsets whose sums are all equal.
输入:
4 3 2 5 1
3
输出:
true
Explanation: It’s possible to divide it into 3 subsets (5), (1, 4), (2,3) with equal sums.

代码(C++完整代码):

#include
#include
#include
using namespace std;

class Solution {
public:
	int target = 0;
	vector<int> help;//用于标记nums中对应下标的元素有没有被选取
	//index:开始位置 cw:当前和 k:还需要找的子集个数
	bool backtrack(vector<int>& nums, int k, int idx, int cw)
	{
		if (k == 0) return true;
		if (cw == target) return backtrack(nums, k - 1, 0, 0);
		for (int i = idx; i < nums.size(); i++)
		{
			if (help[i] == 0 && cw + nums[i] <= target)
			{
				help[i] = 1;
				if (backtrack(nums, k, i + 1, cw + nums[i])) return true;
				help[i] = 0;
			}
		}
		return false;
	}
	bool can(vector<int>& nums, int k)
	{
		int sum = accumulate(nums.begin(), nums.end(), 0);
		if (sum % k)return false;
		int target = sum / k;
		this->target = target;
		help = vector<int>(nums.size(), 0);
		return backtrack(nums, k, 0, 0);
	}
};
int main()
{
	Solution sol;
	int k;
	vector<int> nums;
	int i;
	while (cin >> i)
	{
		nums.push_back(i);
		if (cin.get() == '\n')break;
	}
	cin >> k;
	int n;
	n= sol.can(nums, k);
	if (n == 0)cout << "false" << endl;
	else cout << "true" << endl;
	return 0;
}

运行结果:

OJ刷题------[算法课分支限界法]Partition to K Equal Sum Subsets(划分k个相等的子集)_第1张图片

参考链接:划分k个相等的子集

你可能感兴趣的:(OJ刷题,算法,c++,开发语言)