LeetCode | DP Problems

本文解析了包括组合生成、背包问题、硬币找零等在内的多个经典算法问题,并提供了详细的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

练习上周讲的习题,思路写的比较简单


77. Combinations

Problem
Given two integers n and k, return all possible combinations of k numbers out of 1 … n.

Solution
回溯法,递归调用找到所有组合
算法参考链接 http://www.csie.ntnu.edu.tw/~u91029/Backtracking.html

void combine_assist(vector<vector<int> > &ans, vector<int> &tmp, int n, int k, int st) {
    if (k == 0) {
        ans.push_back(tmp);
    }

    for (int idx = st ; idx <= n; ++idx) {
        tmp.push_back(idx);
        combine_assist(ans, tmp, n, k-1, idx+1);
        tmp.pop_back();
}

vector<vector<int> > combine(int n, int k) {
    vector<vector<int> > ans;
    vector<int> tmp;
    combine_assist(ans, tmp, n, k, 1);
    return ans;
}

416. Partition Equal Subset

Problem
Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.

Note:
Each of the array element will not exceed 100.
The array size will not exceed 200.
Example 1:

Input: [1, 5, 11, 5]

Output: true

Explanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:

Input: [1, 2, 3, 5]

Output: false

Explanation: The array cannot be partitioned into equal sum subsets.

Solution
首先判断和是否为奇数,非偶时一定不能平分
状态: can[i][j]表示前i个数的和可以为j,状态转移 can[i][j] = can[i-1][j] || can[i-1][j-nums[i]].
PS. 初始化j=0和i=0以及判断j与nums[i]大小关系

ool canPartition(vector<int>& nums) {
    if (nums.size() == 0) return true;
    int sum = 0;
    for (int i = 0; i < nums.size(); ++i) 
        sum += nums[i];
    if (sum % 2 == 1) return 0;
    sum /= 2;

    bool can[201][10001];
    for (int i = 0; i < nums.size(); ++i)
        can[i][0] = true;
    for (int i = 0; i <= sum; ++i)
        can[0][i] = false;
    can[0][nums[0]] = true;

    for (int i = 1; i < nums.size(); ++i) {
        for (int j = 0; j <= sum; ++j) {
            can[i][j] = can[i-1][j] || (j>=nums[i]?can[i-1][j-nums[i]]:false);
        }
    }
    return can[nums.size()-1][sum];
}

322. Coin Change

Problem
You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

Example 1:
coins = [1, 2, 5], amount = 11
return 3 (11 = 5 + 5 + 1)

Example 2:
coins = [2], amount = 3
return -1.

Solution
状态 ans[i] 表示值为i时需要的最少硬币数,状态转移: ans[i] = min{ans[i-coints[j]]+1}
PS. 判断i是否大于coints[j] 处理无解状态

int coinChange(vector<int> &coints, int amount) {
    vector<int> ans(amount + 1);
    ans[0] = 0;
    for (int i = 1; i <= amount; ++i) {
        ans[i] = amount + 1;  //INF
        for (int j = 0; j < coints.size(); ++j) {
            if (i >= coints[j] && ans[i - coints[j]] + 1 < ans[i])
                ans[i] = ans[i - coints[j]] + 1;
        }
    }
    return ans[amount]>amount?-1:ans[amount];
}

96. Unique Binary Search Trees

Problem
Given n, how many structurally unique BST’s (binary search trees) that store values 1…n?

Solution
状态ans[i]表示i个连续数字的BST数,状态转移: ans[i] = sum{ans[j-1]*ans[i-j]}
PS. 初始状态: ans[0] = ans[1] = 1;

int numTrees(int n) {
    vector<int> ans(n+1, 1);
    for (int i = 2; i <= n; ++i) {
        ans[i] = 0;
        for (int j = 1; j <= i; ++j) 
            ans[i] += ans[j - 1] * ans[i - j];
    }
    return ans[n];
}

120. Triangle

Problem
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.

For example, given the following triangle
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).

Solution 1
使用用二维数组,从上往下遍历

状态: f[i][j] 到达(i, j)的最小值,状态转移: f[i][j] = min{f[i - 1][j], f[i - 1][j - 1]} + t[i][j]
结果: min{f[t.size()-1][j]}  j = 0 to t.size()
PS. 注意边界条件

int minimumTotal(vector<vector<int>>& triangle) {
    vector<vector<int> > f(2);
    f[0].push_back(triangle[0][0]);
    int idx = 1, pre_idx = 0;
    for (int i = 1; i < triangle.size(); ++i) {
        f[idx].resize(i + 1);
        f[idx][0] = f[pre_idx][0] + triangle[i][0];
        f[idx][i] = f[pre_idx][i-1] + triangle[i][i];
        for (int j = 1; j < triangle[i].size()-1; ++j) {
            f[idx][j] = min(f[pre_idx][j-1], f[pre_idx][j]) + triangle[i][j];
        }
        idx = (idx + 1) % 2;
        pre_idx = (pre_idx + 1) % 2;
    }

    int ans = f[pre_idx][0];
    for (int i = 1; i < triangle.size(); ++i) {
        ans = min(f[pre_idx][i], ans);
    }
    return ans;
}

Solution 2
如果从下往上遍历,那么 f[i][j] 的值只与 f[i+1][j] 和 f[i+1][j+1] 有关。从左往右遍历过程中不会覆盖掉下一步需要用的旧值,因此可以改为一维数组。
状 态: f[j] 到达(i, j)的最小值,状态转移: f[j] = min{f[j], f[j + 1]} + t[i][j]

int minimumTotal(vector<vector<int>>& triangle) {
    vector<int> f(triangle.back());
    for (int i = triangle.size()-2; i >= 0; --i) {
        for (int j = 0; j < triangle[i].size(); ++j) {
            f[j] = min(f[j], f[j + 1]) + triangle[i][j];
        }
    }
    return f[0];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值