Topic
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 is?
Example
Given [1,2,3,4], k=2, target=5. There is 2 solutions:
[1,4] and [2,3], return 2.
Tags Expand
Lintcode Copyright Dynamic Programming
Thinking of solving problems
- Idea one: Iterate, select a point at the beginning, then select the number of k-1 based on the new target value and the new array, and the idea is straightforward. However, there is a duplicate calculation. The complexity of the algorithm is N k , the exponent is incremented, so the calculation is timed out in Lintcode.
- Two ideas: Reference on-line solution, remember that we solve a bunch of numbers, any number of combinations of n the number of the problem? At that time, using a one-dimensional array to store the number can be composed, now we also use a length of target data to store the data, the number of the first j is selected I number, and the composition of the distribution, so the data is dp[i][j][target], plus the next session can be.
Dp[i][j][v]=dp[i][j-1][v]+dp[i-1][j-1][v-a[i]]
Code
Code One
Public class solution { /** * @param a:an integer array. * @param k:a positive integer (k <= Length (a)) * @param target:a integer * @return An integer * / Public int Ksum(intA[],intKintTarget) {if(A.length < K | | k = =0)return 0;if(k = =1){ for(intI=0; i<a.length;i++)if(A[i] = = target)return 1;return 0; }Else{int[] B =New int[A.length-1];if(A.length >1) System.arraycopy (A,1B0, A.length-1);returnKsum (B, K-1, target-a[0]) + Ksum (B, k, target); } }}
Code two
Public class solution { /** * @param a:an integer array. * @param k:a positive integer (k <= Length (a)) * @param target:a integer * @return An integer * / Public int Ksum(intA[],intKintTarget) {int[][][] dp =New int[k +1][a.length +1][target +1]; for(inti =1; I <= a.length; i++) { for(intj = i; J >0; j--) {if(A[j-1] <= target) dp[1][i][a[j-1]] =1; } } for(intm =2; M <= K; m++) { for(intn = m; n <= a.length; n++) { for(intL =0; L <= Target; l++) {Dp[m][n][l] = Dp[m][n][l] + dp[m][n-1][L];if(L + a[n-1] <= target) dp[m][n][l + a[n-1]] = dp[m][n][l + A[n-1]] + dp[m-1][n-1][L]; } } }returnDp[k][a.length][target]; }}
[Lintcode]k Sum