From c88ede927478928962992409c5d70dc35070d3fa Mon Sep 17 00:00:00 2001 From: Kirito <1362050620@qq.com> Date: Thu, 22 Sep 2022 08:55:42 +0800 Subject: [PATCH] Create 1640.cpp --- LeetCode/1640.cpp | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 LeetCode/1640.cpp diff --git a/LeetCode/1640.cpp b/LeetCode/1640.cpp new file mode 100644 index 0000000..91db197 --- /dev/null +++ b/LeetCode/1640.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + bool stepSearch(vector& arr, vector>& pieces, vector& visited, int startIndex) { + for (int i = 0; i < pieces.size(); i++) + { + if (visited[i]) continue; + if (pieces[i][0] != arr[startIndex]) continue; + if (startIndex + pieces[i].size() > arr.size()) continue; + + // check all elements + int j = 1; + for (; j < pieces[i].size(); j++) { + if (arr[startIndex + j] != pieces[i][j]) break; + } + if (j != pieces[i].size()) { + continue; + } + + if (arr.size() == startIndex + pieces[i].size()) return true; + + // step down + visited[i] = true; + bool ret = stepSearch(arr, pieces, visited, startIndex + pieces[i].size()); + visited[i] = false; + + if (ret) return true; + } + + return false; + } + + bool canFormArray(vector& arr, vector>& pieces) { + vector visited(pieces.size(), false); + + return stepSearch(arr, pieces, visited, 0); + } +};