Skip to content

Instantly share code, notes, and snippets.

@cc2011
Created September 5, 2017 05:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cc2011/aa0693b0b48ee9f4dd42f92a2e884b39 to your computer and use it in GitHub Desktop.
Save cc2011/aa0693b0b48ee9f4dd42f92a2e884b39 to your computer and use it in GitHub Desktop.
k-sum
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[][][] dp = new int[n+1][k+1][target+1];
for (int i=0; i <=n; i++) {
dp[i][0][0] = 1;
}
for (int i = 1; i <= n; i++) {
for (int j=1; j <= k && j <= i; j++) {
for(int s = 1; s <= target; s++) {
//dp[i-1][j][s] = 没选i直接等于s
dp[i][j][s] = dp[i-1][j][s];
if (s >= A[i-1]) {
//选 i
dp[i][j][s] += dp[i-1][j-1][s-A[i-1]]; // A index is 0 so i-1
}
}
}
}
//dp[i][j][s] = 前i个里面有多少种方法选j ( j <= k )和为s = 多少
//dp[i-1][j][s] = 没选i直接等于s
return dp[n][k][target];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment