# lintcode - 删除数字

 1 class Solution {
2 public:
3     /*
4      * @param A: A positive integer which has N digits, A is a string
5      * @param l: Remove k digits
6      * @return: A string
7      */
8      string dp[220][220];
9      string inf;
10     string DeleteDigits(string &A, int l) {
11         // write your code here
12         if(A.size() == 0) return "";
13         if(l == 0) return A;
14         int len = A.length() - l;
15         for(int i = 0; i < A.size(); ++i){
16                 dp[i][0] = "";
17                 inf = inf + "9";
18         }
19         for(int i = 0; i < A.size(); ++i){
20                 for(int j = 0; j < A.size(); ++j){
21                         dp[i][j] = inf;
22                 }
23         }
24         vector<string> vec;
25         for(int i = 0; i < A.length(); ++i){
26                 stringstream ss;
27                 ss << (A[i] - '0');
28                 vec.push_back(ss.str());
29         }
30         dp[0][1] = A.substr(0,1);
31         for(int i = 1; i < vec.size(); ++i){
32                         for(int k = 1; k <= i + 1 && k <= len; ++k){
33                                 for(int j = 0; j < i; ++j){
34                                         if(k <= j + 1)
35                                         dp[i][k] = min(dp[j][k - 1] + vec[i], min(dp[i][k], dp[j][k]));
36                                         else dp[i][k] = min(dp[j][k - 1] + vec[i], dp[i][k]);
37
38                                         if(k == 1) dp[i][k] = min(dp[i][k], vec[i]);
39                                 }
40                                // cout << dp[2][1] << endl;
41                         }
42
43         }
44         int len1 = dp[vec.size() - 1][len].length();
45         for(int i = 0; i < len1; ++i){
46                 if(dp[vec.size() - 1][len][i] != '0'){
47                         dp[vec.size() - 1][len] = dp[vec.size() - 1][len].substr(i,len1-i);
48                         break;
49                 }
50         }
51         return dp[vec.size() - 1][len];
52
53     }
54 };

dp[i][j]代表以i结尾，长度为j的最小的字串 因为这个数字会很长 所以不能用数字来dp，必须用字符串来dp 注意一下因为是字符串 所以要去掉前导零

posted @ 2017-09-29 10:44 GeniusYang 阅读(...) 评论(...) 编辑 收藏