当前位置:网站首页>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 .
边栏推荐
- Uniswap founder: no independent token will be issued for genie, and Genie products will be integrated into the uniswap interface
- Machine learning jobs
- Obtain equipment information
- Approximate fair queuing on programmable switches reading notes
- Advanced network accounting notes (VIII)
- FlagAI飞智:AI基础模型开源项目,支持一键调用OPT等模型
- Jerry's adding timer interrupt [chapter]
- 力扣每日一练之字符串Day6
- Is it safe to pay new debts
- Not only Lei Jun, iqoo product manager, praised Qualcomm Xiaolong 8+: a new look
猜你喜欢

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

Summary of accelerating mobile applications at network edge with software programmable FPGA

The yuan universe killer is coming! Xiao Zha offered 4 VR head displays to challenge the visual Turing test

如何避免基因领域“黑天鹅”事件:一场预防性“召回”背后的安全保卫战

Basic knowledge of assembly language (1)

基于微信小程序的婚纱影楼小程序开发笔记

JDBC 在性能测试中的应用

Application of JDBC in performance test

Take out Jianghu will change, and meituan "big brother" is hard to be

Game asset reuse: a new way to find required game assets faster
随机推荐
Uniswap创始人:不会为Genie发行独立代币,Genie产品将集成至Uniswap界面
Obtain equipment information
【对比学习】koa.js、Gin与asp.net core——中间件
pmp考试需要备考多长时间?
Tutorial on installing SSL certificates in Microsoft Exchange Server 2007
How long do you need to prepare for the PMP Exam?
NLP 论文领读|改善意图识别的语义表示:有监督预训练中的各向同性正则化方法
打新债需要具备什么条件 打新债安全吗
Matrix analysis notes (I)
How to make a list sort according to the order of another list
Machine learning jobs
盘点四种WiFi加密标准:WEP、WPA、WPA2、WPA3
Live broadcast review | detailed explanation of koordinator architecture of cloud native hybrid system (complete ppt attached)
硬件开发笔记(六): 硬件开发基本流程,制作一个USB转RS232的模块(五):创建USB封装库并关联原理图元器件
CV background introduction
CV convolution neural network
Develop small programs and official account from zero [phase II]
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
Robust extraction of specific signals with time structure (Part 1)
#19生成器函数经典案例