• 博客园logo
  • 会员
  • 周边
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Lintcode: 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?

Example
Given [1,2,3,4], k=2, target=5. There are 2 solutions:

[1,4] and [2,3], return 2.

当然这道题可以用Recursion的方法,找出所有满足条件的组合,然后求结果arraylist的size,不过对于只需要求多少个可行解的这道题,找出所有满足条件的组合显得过于奢侈了

如果只需要求一个可行解个数,一个3维DP就好了

没有管优化:要注意base case的选取。

我第一次做的时候只定义了 res[0][0][0] = 1, 其实res[i][0][0] = 1, 漏了这些case,所以当时老是过不了

 1 public class Solution {
 2     /**
 3      * @param A: an integer array.
 4      * @param k: a positive integer (k <= length(A))
 5      * @param target: a integer
 6      * @return an integer
 7      */
 8     public int kSum(int A[], int k, int target) {
 9         // write your code here
10         int[][][] res = new int[A.length+1][k+1][target+1];
11         for (int i=0; i<=A.length; i++) {
12             res[i][0][0] = 1;
13         }
14         for (int i=1; i<=A.length; i++) {
15             for (int j=1; j<=k; j++) {
16                 for (int t=1; t<=target; t++) {
17                     if (j > i) res[i][j][t] = 0;
18                     else res[i][j][t] = res[i-1][j][t];
19                     if (t >= A[i-1])
20                         res[i][j][t] += res[i-1][j-1][t-A[i-1]];
21                     
22                 }
23             }
24         }
25         return res[A.length][k][target];
26     }
27 }

 

posted @ 2015-03-07 05:22  neverlandly  阅读(534)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3