474. Ones and Zeroes

寻找单一最优解时,往往采用动态规划的方法,这道题也不例外。
那么第一件事,就是寻找递推公式。
可以考虑构建二维动态规划矩阵,其中need_str_count[i][j]表示,在用i个0,j个1时,可以构建的字符串个数。
若一个字符串demo_str可以被构建,且有a个0,b个1
则应满足:
need_str_count[i][j] = need_str_count[i-a][j-b] + demo_str

注意:这题有个小陷阱,给出的strs中有重复的,所以需要预处理并记录个数。
代码如下:

def solve(strs, m, n):
    def cal_sum(this_dict):
        this_result = 0
        for key, value in this_dict.iteritems():
            this_result += value
        return this_result
    need_str_count = [[{} for j in xrange(n+1)] for i in xrange(m+1)]
    is_cops = [[False for j in xrange(n+1)] for i in xrange(m+1)]
    is_cops[0][0] = True
    with_stat = dict()
    for item in strs:
        if item in with_stat:
            with_stat[item][0] += 1
            continue
        zeros = 0
        ones = 0
        for char in item:
            if char == '0':
                zeros += 1
            else:
                ones += 1
        with_stat[item] = [1, zeros, ones]
    for row in xrange(m+1):
        for col in xrange(n+1):
            for key, item in with_stat.iteritems():
                if item[1] <= row and item[2] <= col:
                    if (key not in need_str_count[row-item[1]][col-item[2]] or
                            (item[0] >
                                need_str_count[row-item[1]][col-item[2]][key]
                             )):
                        if (cal_sum(need_str_count[row][col]) <=
                                cal_sum(
                                    need_str_count[row-item[1]][col-item[2]])):
                            if not is_cops[row-item[1]][col-item[2]]:
                                continue
                            import copy
                            tmp = copy.deepcopy(
                                need_str_count[row-item[1]][col-item[2]]
                            )
                            if key not in tmp:
                                tmp[key] = 1
                            else:
                                tmp[key] += 1
                            need_str_count[row][col] = tmp
                            is_cops[row][col] = True
    max_result = 0
    for each_row in need_str_count:
        for each_one in each_row:
            result = 0
            for key, item in each_one.iteritems():
                result += item
            max_result = max(result, max_result)
    return max_result```
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,768评论 0 33
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,754评论 18 399
  • 个人学习批处理的初衷来源于实际工作;在某个迭代版本有个BS(安卓手游模拟器)大需求,从而在测试过程中就重复涉及到...
    Luckykailiu阅读 4,761评论 0 11
  • 一、 1、请用Java写一个冒泡排序方法 【参考答案】 public static void Bubble(int...
    独云阅读 1,411评论 0 6
  • 上一篇文章,介绍了如何通过vue.js实现绑定列表数据,这篇文章将在上一篇的基础介绍如何响应用户的点击事件。 这里...
    webCoder阅读 20,464评论 0 6