leetcode1049, 474 (0-1 knapsack problem)

本文探讨了如何将0-1背包问题应用到解决实际问题中,如最后的石头重量问题,并通过递归和优化算法来求解。通过实例展示如何从石头重量的计算扩展到字符串组合问题,如最大形式字符串形成。涉及的关键词包括0-1背包、动态规划、矩阵优化和字符串操作。
摘要由CSDN通过智能技术生成

Thinking

The value of the last stone is the difference between the two stone groups. Therefore, we can modify it to a 0-1 knapsack problem.

0-1 knapsack problem definition

Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. Each item is taken or not taken.

Solve for the 0-1 knapsack problem

Define the subproblem  P(i, W) as picking from the top i items with weight not exceeding W. Each item is taken or not taken. The largest value is recorded in m(i, w)

Considering the ith item, there are two choices:

1.Include the current item in the knapsack and recur for remaining items with the knapsack’s decreased capacity.  The problems is changed to P(i-1, W-wi)

2.Exclude the current item from the knapsack and recur for the remaining items. The problem is changed to P(i-1, W)

m(i, W) = max(m(i-1, W), m(i-1, W-wi) + wi)

  (matrix example)

Solution for 1049

Loading...

 class Solution {
    public int lastStoneWeightII(int[] stones) {
        int n = stones.length, sum = 0;
        for (int s : stones) sum += s;
        int goal = sum / 2;
        int[][] m = new int[stones.length + 1][goal + 1];
        for(int p = 1; p < m.length; p++){
            int v = stones[p - 1];
            for(int w = 1; w < m[0].length; w++){
                // w-v is out of bound
                if(v > w){
                    m[p][w] = m[p-1][w];
                }
                else{
                    m[p][w] = Math.max(m[p-1][w], m[p-1][w-v] + v);
                }
            }
        }
        int oneSum = m[stones.length][goal];
        int otherSum = sum - oneSum;
        return Math.abs(oneSum - otherSum);
        
    }
}

Optimization (scrolling array)

When relooking at the transition function: m(i, W) = max(m(i-1, W), m(i-1, W-wi) + wi), we found that m(i, w) is only related to m(i-1). 

Before considering whether or not putting in the ith item, the array records m(i-1).

We need to update the current array in reverse order so that m(i-1, W-wi) can be accessed instead of m(i, W-wi)

Code template

for i=1..N
    for v = V..c[i]
        f[v]=max{f[v],f[v-c[i]]+w[i]};

Optimized Solution for 1049

class Solution {
    public int lastStoneWeightII(int[] stones) {
        int n = stones.length, sum = 0;
        for (int s : stones) sum += s;
        int goal = sum / 2;
        int[] m = new int[goal + 1];
        for(int p = 0; p < stones.length; p++){
            int v = stones[p];
            for(int w = goal; w >= v; w--){
               m[w] = Math.max(m[w], m[w-v] + v);
            }
        }
        int oneSum = m[goal];
        int otherSum = sum - oneSum;
        return Math.abs(oneSum - otherSum); 
    }
}

Solution for 474

Loading...

Using the same template as before. Define a 3-D array instead of a 2-D array because there are two goals( # of 0 and # of 1) we need to take care of. 

One detail to note:

  • j  and  k which keep track of the number of 0s and 1s start from zero instead of 1 (Because a string can be composed of all 0s or 1s)
class Solution {
    public int findMaxForm(String[] strs, int m, int n) {
        int[][][] dp = new int[strs.length + 1][m + 1][n + 1];
        for(int i = 1; i < strs.length + 1; i++){
            int oneCount = 0;
            int zeroCount = 0;
            for(char c : strs[i - 1].toCharArray()){
                if(c == '1'){
                    oneCount++;
                }
                else{
                    zeroCount++;
                }
            }
            for(int j = 0; j < m + 1; j++){
                for(int k = 0; k < n + 1; k++){
                    if(zeroCount > j || oneCount > k){
                        dp[i][j][k] = dp[i-1][j][k];   
                    }
                    else{
                        dp[i][j][k] = Math.max(dp[i-1][j][k], dp[i-1][j - zeroCount][k - oneCount] + 1);
                    } 
                }
            }
        }
        return dp[strs.length][m][n];  
    }
}

Optimized Solution for 474

class Solution {
    public int findMaxForm(String[] strs, int m, int n) {
        int[][] dp = new int[m + 1][n + 1];
        for(int i = 1; i < strs.length + 1; i++){
            int oneCount = 0;
            int zeroCount = 0;
            for(char c : strs[i - 1].toCharArray()){
                if(c == '1'){
                    oneCount++;
                }
                else{
                    zeroCount++;
                }
            }
            for(int j = m; j >= zeroCount; j--){
                for(int k = n; k >= oneCount; k--){  
                  dp[j][k] = Math.max(dp[j][k], dp[j - zeroCount][k - oneCount] + 1);
                }
            }
        }
        return dp[m][n];  
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值