Created
September 5, 2017 05:58
-
-
Save cc2011/aa0693b0b48ee9f4dd42f92a2e884b39 to your computer and use it in GitHub Desktop.
k-sum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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