K Sum | & | |

Source: Internet
Author: User

k Sum

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 .

Analysis:

The first method uses recursion, but it times out.

1  Public classSolution {2     /**3 * @param a:an integer array.4 * @param k:a positive integer (k <= Length (a))5 * @param target:a integer6 * @return an integer7      */8      Public intKsum (intA[],intKinttarget) {9         //Write your code hereTen          One         int[] Total =New int[1]; AHelper (A,0K0, Target,0, total); -         returntotal[0]; -     } the      -      Public voidHelperint[] A,intIndexintKintCountintTargetintTotalint[] KK) { -         if(Count > K | | index >= A.LENGTH | | total > Target)return; -          +Total + =A[index]; -count++; +          A         if(count = = k && Total = =target) { atkk[0]++; -         } -          -Helper (A, index +1, K, count, Target, Total, KK); -Total-=A[index]; -count--; inHelper (A, index +1, K, count, Target, Total, KK); -     } to}

Obviously, the preferred approach is DP. But how to do it? I can't do it. :-( Or just copy paste the other cows ' answers.

F[0][0][0] means that in an empty set to find 0 number, target is 0, then there are 1 solutions, is nothing to pick! In fact, this should be written, that is, to find 0 numbers, the target is 0, there must be 1 solutions:

if (j = = 0 && t = = 0) {
Select 0 number from I to the target:0
D[i][j][t] = 1;
}

1. Status expression:

D[I][J][T] = d[i-1][j][t];
if (T-a[i-1] >= 0) {
D[i][j][t] + = d[i-1][j-1][t-a[i-1]];
}

The meaning is:

(1) We can include the current a[i-1] This value, so we need to add d[i-1][j-1][t-a[i-1] "(if T-A[I-1] is greater than 0)

(2) We can not choose A[i-1] This value, this is the case d[i-1][j][t], that is, directly in the first i-1 values to select some values to target.

1  Public classSolution {2     /**3 * @param a:an integer array.4 * @param k:a positive integer (k <= Length (a))5 * @param target:a integer6 * @return an integer7      */8      Public intKsum (intA[],intKinttarget) {9 Ten         if(Target <0) { One             return 0; A         } -          -         intLen =a.length; the          -         int[][][] D =New int[Len +1][k +1][target +1]; -          -          for(inti =0; I <= Len; i++) { +              for(intj =0; J <= K; J + +) { -                  for(intt =0; T <= Target; t++) { +                     if(J = =0&& T = =0) { A                         //Select 0 number from I to the target:0 atD[I][J][T] =1; -}Else if(! (i = =0|| j = =0|| t = =0)) { -D[I][J][T] = d[i-1][j][t]; -                         if(T-a[i-1] >=0) { -D[i][j][t] + = d[i-1][j-1][t-a[i-1]]; -                         } in                     } -                 } to             } +         } -         returnD[len][k][target]; the     } *}
k Sum II

Given n unique integers, number k (1<=k<=n) and target.

Find all possible k integers where their sum is target.

Has you met this question in a real interview?YesExample

Given [1,2,3,4] , k = 2 , target = 5 . Return:

[  [1,4],  [2,3]]

1  Public classSolution {2     /**3 * @param a:an integer array.4 * @param k:a positive integer (k <= Length (a))5 * @param target:a integer6 * @return A list of lists of integers7      */ 8      PublicArraylist<arraylist<integer>> Ksumii (int[] A,intKinttarget) {9         //Write your code hereTenArraylist<arraylist<integer>> alllist =NewArraylist<arraylist<integer>>(); Onearraylist<integer> list =NewArraylist<integer>(); A         if(A = =NULL|| A.length = =0|| K = =0)returnalllist; -          -Helper (alllist, list,0, A, K,0, Target,0); the         returnalllist; -     } -      -      Public voidHelper (arraylist<arraylist<integer>> alllist, arraylist<integer> list,intIndexint[] A,intKintCountintTargetintTotal ) { +         if(Count > K | | index >= A.LENGTH | | total > Target)return; -          + List.add (A[index]); ATotal + =A[index]; atcount++; -          -         if(count = = k && Total = =target) { -Alllist.add (NewArraylist<integer>(list)); -         } -          inHelper (alllist, list, index +1, A, K, count, Target, total); -Total-= list.Get(List.size ()-1); toList.remove (List.size ()-1); +count--; -Helper (alllist, list, index +1, A, K, count, Target, total); the     } *}

Reference:

http://www.cnblogs.com/yuzhangcmu/p/4279676.html

K Sum | & | |

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.