首页 > 代码库 > k Sum

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 are?

Have you met this question in a real interview? Yes
Example
Given [1,2,3,4], k = 2, target = 5.

There are 2 solutions: [1,4] and [2,3].

Return 2.

状态: 一维的肯定不行, 二维的三个变量轮着试了一下也不行, 干脆把三维的都装上,

方程: 用遍历到当前的状态时, 用不用的上当前的元素(如何判断, 根据题意和当前元素的有无对另一维状态变量的改变来判断)来划分情况, 然后看看是状态相加还是 求最大, 还是怎么的

初始化边界点很重要:

注意size都是多加一, 但是在数组和string 时注意-1 表示当前的位置, 如:

if (l >= A[i - 1]) {
public int kSum(int A[], int k, int target) {
        // write your code here
        //state 
        int n = A.length;
        int[][][] f = new int[n + 1][k + 1][target + 1];
        
        //initialize
        for (int i = 0; i <= n; i++) {
            f[i][0][0] = 1;
        }
        
         //function
        for (int i = 1; i <= n; i++) {
             for (int j = 1; j <= k && j <= i; j++) {
                 for (int l = 1; l <= target; l++) {
                     
                    f[i][j][l] = f[i - 1][j][l];
                    if (l >= A[i - 1]) {
                        f[i][j][l] += f[i - 1][j - 1][l - A[i - 1]];
                    }
                }
            }
        }
        
        return f[n][k][target];
    }

  

k Sum