DP:
|
|
没人会想用二维segtree写吧我全当练手了:
|
|
DP:
|
|
没人会想用二维segtree写吧我全当练手了:
|
|
standard segment tree
|
|
class Solution {
unordered_map
public:
bool wordBreak(string s, unordered_set
map
for (auto word: wordDict) {
mp[word[0]].push_back(word);
}
res[“”] = true;
return helper(s, mp);
}
bool helper(string s, map
if (res.find(s) != res.end()) {
return res[s];
}
for (auto word:wordDict[s[0]]) {
if (s.substr(0, word.length()) == word) {
if (helper(s.substr(word.length()), wordDict)) {
res[s] = true;
return true;
}
}
}
res[s] = false;
return false;
}
};
|
|
一开始是Trie+backtracking,会TLE。
|
|
于是加上memorization,把临时的结果储存起来。不过这里backtracking也得修改成有返回值的函数,res也变成局部变量,不等到搜索到字符串结尾再push_back,而是返回局部解。这算是DP了吧。beats 71.48%, 还没想到哪里可以优化。
|
|
学习一个如何split string。
|
|
或者:
|
|
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
![]()
|
|
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
|
|
O(1) space solution: 一个很好的思路,int有四个字节,只用了一位,可以用第二位来表示下一个status。注意count neighbor的时候会否把自己算进去。
|
|
O(1) space解法很妙,把row/col有0的情况记录在第一排/第一列,但(0, 0)的点要注意,不能用来同时表示第一排和第一列,选择一个以后用另外的bool来单独表示另一个。再根据这m+n个0/1来更新全部的格子。
|
|
You are playing the following Flip Game with your friend: Given a string that contains only these two characters: + and -, you and your friend take turns to flip two consecutive “++” into “–”. The game ends when a person can no longer make a move and therefore the other person will be the winner.
Write a function to determine if the starting player can guarantee a win.
For example, given s = “++++”, return true. The starting player can guarantee a win by flipping the middle “++” to become “+–+”.
一开始写的算法是只要能赢就返回true,但题意是guarantee,即对手无论如何下都能保证赢。无奈刚过subscription时间,无法提交验证他们提供的test cases。
|
|
discussion里有更简洁的做法,在每次canWin里只考虑一方是否能赢,而不是先手下完再用一个循环考虑后手,两步之后再递归。
|
|
(ref: https://discuss.leetcode.com/topic/63191/c-backtracking-with-memorization-26ms)