当前位置:网站首页>LeetCode 1079. movable-type printing
LeetCode 1079. movable-type printing
2022-06-23 19:28:00 【51CTO】

Want to see more algorithm problems , You can scan the QR code above to follow my wechat official account “ Data structures and algorithms ”, Up to now, I have been in the official account Updated 500 Multiple algorithm problems , Some of them have been sorted into pdf file , Up to now, there are a total of 1000 Multi page ( And it will continue to increase ), You can reply to keywords in the official account “pdf” You can download it. .

Backtracking algorithm solves
This question is actually how many different combinations of input characters can be formed . I've talked about many similar problems before
《391, Backtracking algorithm for combinatorial problems 》 《448, Combined solutions 》 《451, Backtracking and bit operations solve subsets 》
But the difference is that the order of the characters in the previous questions will not change , For example 451 topic , His subset is 123, But there can be no 321. But the question is different , Input AAB, In his sequence ,A Can be in B It can also be in front of B Behind . So how to solve this problem using backtracking algorithm , Let's take an example 1 Let's draw a picture for example

Several combination backtracking algorithms introduced earlier , Because the results can't be repeated ( such as [1,3] and [3,1] It is considered to be the result of repetition ), So every time you choose, you can only choose from the past . But this problem subset [A,B] and [B,A] It is considered to be two different results , So choose from the beginning every time , Because each character can only be used once , So if you use it, you can't use it next time , You can use an array here visit To mark whether it has been used .
But the difficulty here is how to filter out the gray part in the above figure ( That's the repetitive part ). for instance , such as ABBCD, If we choose the second 1 individual B, Then the rest of the characters become ABCD, At this time, we will choose the second 2 individual B Yes. . But if we don't choose the second 1 individual B, Choose the second one directly 2 individual B, Then the remaining characters are ABCD, It's repeated above . So the code looks like this
Let's talk about 《450, What is a backtracking algorithm , As soon as we see it , As soon as you write it, it's useless 》 When , The template of backtracking algorithm has been mentioned many times
private
void
backtrack(
" Original parameters ") {
// Termination conditions ( Recursion must have a termination condition )
if (
" Termination conditions ") {
// Some logic operations ( not essential , As the case may be )
return;
}
for (
int
i
=
"for The parameters at the beginning of the loop ";
i
<
"for Parameters at the end of the loop ";
i
++) {
// Some logic operations ( not essential , As the case may be )
// Make a choice
// recursive
backtrack(
" New parameters ");
// Some logic operations ( not essential , As the case may be )
// Unselect
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
Finally, let's look at the final code of this problem
public
int
numTilePossibilities(
String
tiles) {
char[]
chars
=
tiles.
toCharArray();
// Prioritize , The goal is to have the same characters next to , In the following calculation, we can filter out the duplicate
Arrays.
sort(
chars);
int[]
res
=
new
int[
1];
backtrack(
res,
chars,
new
boolean[
tiles.
length()],
tiles.
length(),
0);
return
res[
0];
}
private
void
backtrack(
int[]
res,
char[]
chars,
boolean[]
used,
int
length,
int
index) {
// If there is nothing to choose from, return to
if (
index
==
length)
return;
// Be careful , there i Every time from 0 At the beginning , Not from index Start
for (
int
i
=
0;
i
<
length;
i
++) {
// A character can only be selected once , If the current character has been selected , You can't choose any more .
if (
used[
i])
continue;
// Filter out duplicate results
if (
i
-
1
>=
0
&&
chars[
i]
==
chars[
i
-
1]
&&
!
used[
i
-
1])
continue;
// Select the current character , And mark it as selected
used[
i]
=
true;
res[
0]
++;
// Choose a character , One more result
// The next branch continues recursion
backtrack(
res,
chars,
used,
length,
index
+
1);
// Restore it after use .
used[
i]
=
false;
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
Here can also be written in another way , First count the number of each character , And then use , The code is as follows . The principle is similar , But he doesn't have to be heavy , Because there's no possibility of repetition here .
public
int
numTilePossibilities(
String
tiles) {
char[]
chars
=
tiles.
toCharArray();
// Count the number of each character
int[]
count
=
new
int[
26];
for (
char
c :
chars)
count[
c
-
'A']
++;
int[]
res
=
new
int[
1];
backtrack(
res,
count);
return
res[
0];
}
private
void
backtrack(
int[]
res,
int[]
arr) {
// Traverse all the characters
for (
int
i
=
0;
i
<
26;
i
++) {
// If the current character is used up, look for the next
if (
arr[
i]
==
0)
continue;
// If it's not used up, keep using it , And then subtract the number of characters 1
arr[
i]
--;
// Use one character , The number of subsets will be one more
res[
0]
++;
backtrack(
res,
arr);
// After the current character is used , Restore the number of it
arr[
i]
++;
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
summary
I have also introduced many problems about backtracking algorithm , The backtracking algorithm has a general template , Just master this template , And then for different questions in slightly modified , Basically, it can be done .
边栏推荐
- Advanced network accounting notes (III)
- Matrix analysis notes (I)
- JDBC 在性能测试中的应用
- Jerry's seamless looping [chapter]
- Ges graph computing engine hyg unveils the secrets of Graph Segmentation
- 直播回顾 | 云原生混部系统 Koordinator 架构详解(附完整PPT)
- 盘点四种WiFi加密标准:WEP、WPA、WPA2、WPA3
- 【One by One系列】IdentityServer4(三)使用用户名和密码
- Cloud security daily 220623: the red hat database management system has found an arbitrary code execution vulnerability and needs to be upgraded as soon as possible
- Helix QAC is updated to 2022.1 and will continue to provide high standard compliance coverage
猜你喜欢

Vprom notes

直播回顾 | 云原生混部系统 Koordinator 架构详解(附完整PPT)

Leetcode daily question - 30 Concatenate substrings of all words

NAACL 2022 Findings | 字节提出MTG:多语言文本生成数据集

Application de JDBC dans les essais de performance

8、AI医生案例

博睿数据出席阿里云可观测技术峰会,数字体验管理驱动可持续发展

火线沙龙第26期-多云安全专场

Graffiti intelligence passed the hearing: Tencent is an important shareholder planning to return to Hong Kong for listing
![Develop small programs and official account from zero [phase I]](/img/02/77386ba3fe50b16018f77115b99db6.png)
Develop small programs and official account from zero [phase I]
随机推荐
Vprom notes
混沌工程,了解一下
Are there conditions for making new bonds? Is it safe to make new bonds
Application of JDBC in performance test
手把手写深度学习(15):在Hugging Face上构建自己的语料库
Noah fortune passed the hearing: with an annual revenue of 4.3 billion yuan, Wang Jingbo has 49% voting rights, and Sequoia is a shareholder
【One by One系列】IdentityServer4(八)使用EntityFramework Core对数据进行持久化
Function definition and function parameters
Helix QAC is updated to 2022.1 and will continue to provide high standard compliance coverage
Jerry's adding timer interrupt [chapter]
【NOI2014】15. Difficult to get up syndrome [binary]
Pisces: a programmable, protocol independent software switch (summary)
Yaxiang spice listed on Shenzhen Stock Exchange: with a market value of 4billion, Dinglong Bohui and Yongyao investment are shareholders
基于 ShardingSphere 的得物数据库中间件平台“彩虹桥”演进之路
Advanced network accounting notes (III)
Browser cross domain
【One by One系列】IdentityServer4(七)授权码流程原理之MVC
Develop small programs and official account from zero [phase I]
如何避免基因领域“黑天鹅”事件:一场预防性“召回”背后的安全保卫战
Definition and model of indicators (complex indicators)