leetcode 698. Partition to K Equal Sum Subsets(记忆化搜索/状压dp)

题目:https://leetcode.com/contest/leetcode-weekly-contest-54/problems/partition-to-k-equal-sum-subsets/
题意:给你一个数组和k,问能否将数组分为k组,且k组数的和相等
思路:记忆化搜索
代码:

int n,kk,aver,f[20];
class Solution {
public:
    bool flag = false;
    void dfs(int cnt,vector<int>& a){
        if(flag)
            return;
        if(cnt == n){
            for(int i = 0;i < kk;i++)
                if(f[i] != aver)
                    return;
            flag = true;
            return;
        }
        for(int i = 0;i < kk;i++){
            if(f[i] + a[cnt] <= aver){
                f[i] += a[cnt];
                dfs(cnt+1,a);
                f[i] -= a[cnt];
            }
        }
        return;
    }
    bool canPartitionKSubsets(vector<int>& nums, int k) {
        memset(f,0,sizeof(f));
        n = nums.size();kk = k;
        int sum = 0;
        for(auto x : nums) sum += x;
        if(sum % k != 0)
            return false;
        aver = sum / k;
        sort(nums.begin(),nums.end());
        reverse(nums.begin(),nums.end());
        dfs(0,nums);
        return flag;
    }
};

状压dp(贴个官方题解的):

class Solution {
    public boolean canPartitionKSubsets(int[] nums, int k) {
        int N = nums.length;
        Arrays.sort(nums);
        int sum = Arrays.stream(nums).sum();
        int target = sum / k;
        if (sum % k > 0 || nums[N - 1] > target) return false;

        boolean[] dp = new boolean[1 << N];
        dp[0] = true;
        int[] total = new int[1 << N];

        for (int state = 0; state < (1 << N); state++) {
            if (!dp[state]) continue;
            for (int i = 0; i < N; i++) {
                int future = state | (1 << i);
                if (state != future && !dp[future]) {
                    if (nums[i] <= target - (total[state] % target)) {
                        dp[future] = true;
                        total[future] = total[state] + nums[i];
                    } else {
                        break;
                    }
                }
            }
        }
        return dp[(1 << N) - 1];
    }
}

你可能感兴趣的:(动态规划,搜索)