DP啊DP

DP问题的特征:

  1. An instance is solved using the solutions for smaller instances.
  2. The solution for a smaller instance might be needed multiple times.
  3. The solutions to smaller instances are stored in a table, so that each smaller instance is solved only once.
  4. Additional space is used to save time.

-----------------------------------------------------------------------

From Leetcode: 

1. Edit distance
2. Word Break


3. Longest Palindromic Substring
4. Maximum Subarray

---------------------------------------------------------------------
From Topcoder:

求最:

1, Given a list of N coins, their values (V1V2, ... , VN), and the total sum S. Find the minimum number of coins the sum of which is S (we can use as many coins of one type as we want), or report -1 if it's not possible to select coins in such a way that they sum up to S

 public int getMin(int[] A, int s) {
        if (A == null || A.length == 0) {
            return -1;
        }

        int[] res = new int[s + 1];

        for (int i = 1; i < res.length; i++) {
            res[i] = Integer.MAX_VALUE;
            for (int j = 0; j < A.length; j++) {
                if (A[j] <= i) {
                    int pre = res[i - A[j]];
                    if (pre < Integer.MAX_VALUE) {
                        res[i] = Math.min(pre + 1, res[i]);
                    }
                }
            }
        }

        return res[s] < Integer.MAX_VALUE ? res[s] : -1;
    }


2, Given a sequence of N numbers A[1] A[2] , ..., A[N] . Find the length of the longest non-decreasing sequence.
辅助的array存储含有s[i]作为末尾元素的non-decreasing sub-sequence的长度
 public static int getLength(int[] s) {
        if (s == null || s.length == 0) {
            return 0;
        }

        int max = 0;
        int[] lenSeq = new int[s.length];

        for (int i = 0; i < lenSeq.length; i++) {
            lenSeq[i] = 1;
            for (int j = 0; j < i; j++) {
                if (s[i] >= s[j]) {
                    lenSeq[i] = Math.max(lenSeq[i], lenSeq[j] + 1);
                    max = Math.max(max, lenSeq[i]);
                }
            }
        }
        return max;
}

参考:
X WANG: http://www.programcreek.com/2012/11/top-10-algorithms-for-coding-interview/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值