代码随想录算法训练营第四十五天|● 1049. 最后一块石头的重量 II ● 494. 目标和 ● 474.一和零

1049. 最后一块石头的重量 II

dp[j] : 容量为j的背包最多可以装dp[j]重的石头

int max(int a, int b) {
    return (a > b) ? a : b;
}

int lastStoneWeightII(int* stones, int stonesSize){
    int sum=0, target=0;
    for (int i=0; i=stones[i]; j--)
        {
            dp[j] = max(dp[j], dp[j - stones[i]] + stones[i]);
        }
    }
    //  剩下的一半重量为sum - dp[target]
    return sum - dp[target] - dp[target];
}

494. 目标和

求的是装满背包的方法

int findTargetSumWays(int* nums, int numsSize, int target){
  int sum = 0;
  for (int i=0; i sum || (sum - target)%2)
    return 0;
  int k = (sum - target)/2;
  int dp[k+1];
  memset(dp, 0, sizeof(int) * (k+1));
  int i, j;
  dp[0] = 1;
  for (i=0; i=nums[i]; j--)
    {
      dp[j] += dp[j - nums[i]];
    }
  }
  return dp[k];
}
int findTargetSumWays(int* nums, int numsSize, int target){
  int sum = 0;
  for (int i=0; i sum || (sum + target)%2)
    return 0;
  int k = (sum + target)/2;
  int dp[k+1];
  memset(dp, 0, sizeof(int) * (k+1));
  int i, j;
  dp[0] = 1;
  for (i=0; i=nums[i]; j--)
    {
      dp[j] += dp[j - nums[i]];
    }
  }
  return dp[k];
}

474. 一和零

void getZerosOnes(int* zerosOnes, char* str)
{
    int length = strlen(str);
    for (int i = 0; i < length; i++)
    {
        zerosOnes[str[i] - '0']++;
    }
}

int findMaxForm(char ** strs, int strsSize, int m, int n){
    int length = strsSize;
    int dp[m+1][n+1];
    memset(dp, 0, sizeof(dp));
    int i, j, k;
    for (i = 0; i < length; i++)
    {
        int zerosOnes[2];
        memset(zerosOnes, 0, sizeof(zerosOnes));
        getZerosOnes(zerosOnes, strs[i]);
        int zeros = zerosOnes[0];
        int ones  = zerosOnes[1];
        for (j = m; j >= zeros; j--)
        {
            for (k = n; k >= ones; k--)
            {
                dp[j][k] = fmax(dp[j][k], dp[j - zeros][k - ones] + 1);
            }
        }
    }
    return dp[m][n];
}

你可能感兴趣的:(代码随想录算法,算法,数据结构,leetcode,c语言)