当前位置:网站首页>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 .
边栏推荐
- qgis导入WMS OR WMTS
- Comparison and evaluation of digicert and globalsign single domain ov SSL certificates
- 盘点四种WiFi加密标准:WEP、WPA、WPA2、WPA3
- 火线沙龙第26期-多云安全专场
- Application of JDBC in performance test
- Design of hardware switch with programmable full function rate limiter
- Vprom notes
- Naacl 2022 finds | byte proposes MTG: multilingual text generation data set
- 手把手写深度学习(15):在Hugging Face上构建自己的语料库
- 盘点四种WiFi加密标准:WEP、WPA、WPA2、WPA3
猜你喜欢

混沌工程,了解一下

从零开发小程序和公众号【第二期】
![Jerry's serial port communication serial port receiving IO needs to set digital function [chapter]](/img/a6/bf78f9c4c26a9a996284e474114ce0.png)
Jerry's serial port communication serial port receiving IO needs to set digital function [chapter]
![【NOI2014】15. Difficult to get up syndrome [binary]](/img/3a/12e9b2566d3ca3330a3cc6c5eaf135.png)
【NOI2014】15. Difficult to get up syndrome [binary]

What are the useful personnel management software? Personnel management system software ranking!

Application de JDBC dans les essais de performance

Graffiti intelligence passed the hearing: Tencent is an important shareholder planning to return to Hong Kong for listing

A review of comparative learning

游戏资产复用:更快找到所需游戏资产的新方法

Netcf summary
随机推荐
混沌工程,了解一下
Dataease template market officially released
打新债有何要求 打新债安全吗
【One by One系列】IdentityServer4(三)使用用户名和密码
Definition and model of indicators (complex indicators)
Borui data attends Alibaba cloud observable technology summit, and digital experience management drives sustainable development
打新债 要求 打新债安全吗
#19生成器函数经典案例
Function definition and function parameters
Basic knowledge of assembly language (1)
Matrix analysis notes (III-1)
NAACL 2022 Findings | 字节提出MTG:多语言文本生成数据集
金鱼哥RHCA回忆录:DO447管理用户和团队的访问--用团队有效地管理用户
Shengke communication IPO meeting: annual revenue of 460million China Zhenhua and industry fund are shareholders
[one by one series] spa of identityserver4 (VI) authorization code process principle
Idea console displays Chinese garbled code
基于 ShardingSphere 的得物数据库中间件平台“彩虹桥”演进之路
Matrix analysis notes (II)
硬件开发笔记(六): 硬件开发基本流程,制作一个USB转RS232的模块(五):创建USB封装库并关联原理图元器件
CV fully connected neural network