leetcode 854. K-Similar Strings
给定两个字符串, 判断最少经过多少次swap 可以使得 两个字符串一致,
首先类似的问题 是存在一个 underlying graph 的。
每一个字母都对应着一个节点,两个字符串的不一致表示为图上的一条有向边
最后的问题转化为 图上的最(多)圆环分解
要注意的是贪心策略并不能解决问题(即每一次都选择 最小的那个圆环构成原图)
1
使用记忆化搜索策略。
将一个所有可能存在路径存在与否的向量作为相应的状态
超时的代码
class Solution:
def kSimilarity(self, A, B):
"""
:type A: str
:type B: str
:rtype: int
"""
if (A==B):
return 0
N = len(A)
alp ='abcdef'
pairs = [(a,b) for a in alp for b in alp if a!=b]
# 所有可能的路径
index = {p:i for i,p in enumerate(pairs)}
# 所有可能的路径的编号
count = [0]*len(index)
#可能路径的数目(原图) 也就是初始状态
for a,b in zip(A,B):
if(a!=b):
count[index[(a,b)]]= count[index[a,b]]+ 1
seen = set()
#所有可能出现的环
for size in range(2,len(alp) + 1):
for cand in itertools.permutations(alp,size):
# 最小的哪一个出发节点为是顺序(防止重复)
i = cand.index(min(cand))
seen.add (cand[i:]+cand[:i])
possibles = [] #所有可能的环的路径表示 状态之间的 路径
for cand in seen:
row = [0] * len(alp)*(len(alp)-1)
for a,b in zip(cand,cand[1:]+cand[:1]):
row[index[a,b]]= row[index[a,b]]+1
possibles.append(row)
ZERO = tuple([0]*len(row))
memo = {ZERO:0}
# print(possibles)
def solve(count):
if count in memo :
return memo[count]
ans =float('-inf')
#所有可能的路径
for row in possibles :
count2 = list(count)
for i,x in enumerate(row):
if count2[i]>=x :
count2[i] = count2[i] - x
else:
break
else:
ans = max(ans,1 + solve(tuple(count2)))
memo[count]= ans
return ans
return sum(count)-solve(tuple(count))
2 暴力进行广度优先搜索
因为可以证明最优解可以是永远更换第一个不匹配的字母到合适的位置,那么我可以将一个节点的边数目由 N2 下降到N
而并不是所有意义上的交换 这种复杂度降低是非常有必要的
结论: 这种数据量比较小的问题往往比较复杂,尤其可能没有多项式解
class Solution:
def kSimilarity(self, A, B):
"""
:type A: str
:type B: str
:rtype: int
"""
def nei(S):
for i,c in enumerate(S):
if c!= B[i]:
break
T=list(S)
for j in range(i+1,len(S)):
if(S[j]==B[i]):
T[i],T[j]= T[j],T[i]
yield "".join(T)
T[j],T[i]=T[i],T[j]
queue= collections.deque([A])
seen ={A:0}
while(queue):
S=queue.popleft()
if(S==B):
return seen[S]
for T in nei(S):
if T not in seen:
seen[T]=seen[S]+1
queue.append(T)
这里有一个 fiield 迭代器的用发 可以学习一个
leetcode 854. K-Similar Strings的更多相关文章
- [LeetCode] 854. K-Similar Strings 相似度为K的字符串
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two ...
- [链表]LeetCode 25 K组一个翻转链表
LeetCode 25 k组一个翻转链表 TITLE 示例 1: 输入:head = [1,2,3,4,5], k = 2 输出:[2,1,4,3,5] 示例 2: 输入:head = [1,2,3, ...
- 【LeetCode】1400. 构造 K 个回文字符串 Construct K Palindrome Strings
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 统计奇数字符出现次数 日期 题目地址:https:// ...
- Baozi Leetcode Solution 205: Isomorphic Strings
Problem Statement Given two strings s and t, determine if they are isomorphic. Two strings are isomo ...
- [LeetCode] 555. Split Concatenated Strings 分割串联字符串
Given a list of strings, you could concatenate these strings together into a loop, where for each st ...
- 【LeetCode】43. Multiply Strings 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...
- [LeetCode] Remove K Digits 去掉K位数字
Given a non-negative integer num represented as a string, remove k digits from the number so that th ...
- [LeetCode] Find K Pairs with Smallest Sums 找和最小的K对数字
You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k. Define ...
- [LeetCode] Top K Frequent Elements 前K个高频元素
Given a non-empty array of integers, return the k most frequent elements. For example,Given [1,1,1,2 ...
随机推荐
- delphi 流程单打印
1.添加声明 f_count1: double; 2.得到拆分页数量 // Modified by 884 2018-04-20 14:50:18 AM0057 with aqTpCount do b ...
- 阿里云在云栖大会发布SaaS加速器3.0版最新成果,让天下没有难做的SaaS
2019年杭州·云栖大会顺利落幕,超过6万人次观展,200余位顶尖科学家分享了前沿技术.作为“阿里云不做SaaS”,坚持“被集成”战略的落地体现,阿里云SaaS加速器在云栖大会现场发布了SaaS加速器 ...
- 弹性网卡支持私网多IP
摘要: 弹性网卡支持多IP功能可以最多在一块弹性网卡配置20个私网IP地址,特别适用于于以下场景. 1.单个服务器上托管多个应用,提升实例利用率,每个应用对外暴露一个独立的服务IP地址. 2.当实例发 ...
- Vue项目组织规范
目录 一.项目结构的核心思想 二.项目目录结构 三.资源路径编译规则 四.index.html 五.build目录 和 config目录 六.public目录 七.static 目录 八.src目录结 ...
- VIM 代码自动补全, YouCompleteMe安装及配置
效果 下载 使用Vundle安装 YCM 1. 安装Vundle window用户安装vundle参考这里:Windows下 vundle的安装和使用 2.
- shell常用命令及正则辅助日志分析统计
https://www.cnblogs.com/wj033/p/3451618.html 正则日志分析统计 3 grep 'onerror' v3-0621.log | egrep -v '(\d ...
- PAT甲级——A1134 Vertex Cover【25】
A vertex cover of a graph is a set of vertices such that each edge of the graph is incident to at le ...
- Python对接支付宝支付自实现
Python对接支付宝支付自实现 # -*- coding: utf-8 -*- import base64 import json import urllib.parse from datetime ...
- HYNB Round 8: 2016 ICPC Amritapuri Regionals
HYNB Round 8: 2016 ICPC Amritapuri Regionals A - Tim and BSTs 做法 经典的树 DP 问题. \(dp[u][i]\) 表示考虑以 u 为根 ...
- easyui combotree的使用示例
一.View: 1.定义输入控件 <input id="ParentId" name="ParentId"> 2.绑定combotree $('#P ...