k Sum
Posted flagyuri
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了k Sum相关的知识,希望对你有一定的参考价值。
Description
Given n distinct positive integers, integer k (k <= n) and a number target.
Find k numbers where sum is target. Calculate how many solutions there are?
Example
Example 1
Input:
List = [1,2,3,4]
k = 2
target = 5
Output: 2
Explanation: 1 + 4 = 2 + 3 = 5
Example 2
Input: List = [1,2,3,4,5] k = 3 target = 6 Output: 1 Explanation: There is only one method. 1 + 2 + 3 = 6
思路:采用动态规划(dp)的思想,进行状态转移,记录数字和和出现次数之间的关系。
用dp[i][j][k]dp[i][j][k]表示前ii个数里选jj个和为k的方案数。
public class Solution { /** * @param A: An integer array * @param k: A positive integer (k <= length(A)) * @param target: An integer * @return: An integer */ public int kSum(int[] A, int k, int target) { int n = A.length; int[][][] f = new int[n + 1][k + 1][target + 1]; for (int i = 0; i < n + 1; i++) { f[i][0][0] = 1; } for (int i = 1; i <= n; i++) { for (int j = 1; j <= k && j <= i; j++) { for (int t = 1; t <= target; t++) { f[i][j][t] = 0; if (t >= A[i - 1]) { f[i][j][t] = f[i - 1][j - 1][t - A[i - 1]]; } f[i][j][t] += f[i - 1][j][t]; } // for t } // for j } // for i return f[n][k][target]; } }
以上是关于k Sum的主要内容,如果未能解决你的问题,请参考以下文章