n
名士兵站成一排。每個士兵都有一個 獨一無二 的評分 rating
。
每 3 個士兵可以組成一個作戰單位,分組規則如下:
- 從隊伍中選出下標分別爲
i
、j
、k
的 3 名士兵,他們的評分分別爲rating[i]
、rating[j]
、rating[k]
- 作戰單位需滿足:
rating[i] < rating[j] < rating[k]
或者rating[i] > rating[j] > rating[k]
,其中0 <= i < j < k < n
請你返回按上述條件可以組建的作戰單位數量。每個士兵都可以是多個作戰單位的一部分。
示例 1:
輸入:rating = [2,5,3,4,1] 輸出:3 解釋:我們可以組建三個作戰單位 (2,3,4)、(5,4,1)、(5,3,1) 。
示例 2:
輸入:rating = [2,1,3] 輸出:0 解釋:根據題目條件,我們無法組建作戰單位。
示例 3:
輸入:rating = [1,2,3,4] 輸出:4
提示:
n == rating.length
1 <= n <= 200
1 <= rating[i] <= 10^5
class Solution {
public:
int numTeams(vector<int>& rating) {
if (rating.size() < 3) {
return 0;
}
int count = 0, num = 0;
vector<int> nums;
Permute(rating, 0, nums,num, count);
return num;
}
void Permute(vector<int>& rating, int index, vector<int>& res, int& num, int count) {
if (res.size() == 3) {
if ((res[0] > res[1] && res[1] > res[2]) ||
(res[0] < res[1] && res[1] < res[2])) {
num += 1;
}
return ;
}
if (index >= rating.size()) {
return ;
}
for (int i = index; i < rating.size(); ++i) {
res.push_back(rating[i]);
Permute(rating, i + 1, res, num, count - 1);
res.pop_back();
}
}
};