zoukankan      html  css  js  c++  java
  • 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];
        }
    

      

  • 相关阅读:
    进程通信方式-管道pipe
    进程间通信
    信号的发送与处理
    信号应用于事件通知
    信号的屏蔽,信号集
    信号的发送kill,raise,alarm,setitimer,abort,sigqueue
    信号处理函数的返回sigsetjmp/siglongjmp
    POJ 1562 Oil Deposits
    HDU 1016 Prime Ring Problem
    HDU 1010 Tempter of the Bone
  • 原文地址:https://www.cnblogs.com/apanda009/p/7294358.html
Copyright © 2011-2022 走看看