动态规划---数组等子集和问题总结

1.能否划分成2个相等和的子数组,转化为0-1背包问题,何为sum/2,二重循环从大到小遍历
动态规划---数组等子集和问题总结_第1张图片

#include 
#include 
#include
using namespace std;

bool canPartion(vectornums) {
    int sum = 0;
    for (int i = 0; i < nums.size(); i++) {
        sum += nums[i];
    }
    if (sum % 2 == 1) {
        return false;
    }
    int target = sum / 2;
    vector dp(target + 1, 0);
    for (int i = 0; i < nums.size(); i++) {
        for (int j = target; j >= nums[i]; j--) {
            dp[j] = max(dp[j], dp[j-nums[i]] + nums[i]);
        }
    }
    std::cout << dp[target] << "  " << target << endl;
    return dp[target] == target;
}
int main()
{
    vector nums = {1, 5, 11, 5};
    cout << canPartion(nums) << endl;
    return 0;
}

2。能否划分成k个和相同数组,直接递归
动态规划---数组等子集和问题总结_第2张图片

#include 
#include 
#include
#include
using namespace std;

bool dfs(vector &nums, vector &visited, int start, int k, int cur_sum, int target) {
    if (k == 1) return true;
    if (target < cur_sum) return false;
    if (target == cur_sum) return dfs(nums, visited, 0, k - 1, 0, target);
    for (int i = start; i < nums.size(); i++) {
        if (visited[i]) continue;
        visited[i] = 1;
        
        if(dfs(nums, visited, i + 1, k, cur_sum + nums[i], target)) {
            return true;
        }
        visited[i] = 0;
        
    }
    
    return false;
}
int main()
{
    vector nums = {4, 3, 2, 3, 5, 2, 1};
    int sum = 0;
    for (auto num : nums) {
        sum += num;
    }
    int k = 4;
    if (sum % k !=0 ) {
        cout <<"error" <());
    vector visited(nums.size(), 0);
    cout << dfs(nums, visited, 0, k, 0, sum / k) << "   " << sum / k <

你可能感兴趣的:(c++)