一、Problem
輸入
輸入一個整數 n,表示數列元素的個數。
輸出
輸出山峯排列的個數。
3
4
共有以下4種方案: 123、132、231、321
數據規模
對於60%的數據 n <= 10
對於100%的數據 n <= 60
二、Solution
方法一:全排列
這瞎寫了…的 9/18 分,全排列一下,判斷一下…
import java.util.*;
import java.math.*;
import java.io.*;
public class Main{
static class Solution {
int[] a;
int n, res;
boolean has() {
boolean down = false;
for (int i = 0; i < n-2; i++) {
if (a[i] > a[i+1])
down = true;
if (down && a[i+1] < a[i+2])
return true;
}
return false;
}
void dfs(int k) {
if (k == n) {
if (!has())
res++;
return;
}
for (int i = k; i < n; i++) {
swap(a, i, k);
dfs(k+1);
swap(a, i, k);
}
}
void swap (int[] a, int l, int r) {
int t = a[l];
a[l] = a[r];
a[r] = t;
}
void init() {
Scanner sc = new Scanner(new BufferedInputStream(System.in));
BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out));
n = sc.nextInt();
if (n <= 2) {System.out.println(n); return;}
a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = i+1;
}
dfs(0);
System.out.println(res);
}
}
public static void main(String[] args) throws IOException {
Solution s = new Solution();
s.init();
}
}
複雜度分析
- 時間複雜度:,
- 空間複雜度:,
方法二:找規律
比如 1、2、3、4、5,當 4 在第三個位置時,前面的兩個數構成升序序列,後面的兩個數構成降序序列。前面兩個數通過 選出,後面的三個數肯定也就確定了。這樣,所有滿足條件的排序數位 ,即由二項式定理得結果爲 。
關於冪運算,提供兩種方法:
- 位運算
- 快速冪
import java.util.*;
import java.math.*;
import java.io.*;
public class Main{
static class Solution {
long quick(long b, long p) {
long res = 1;
while (p > 0) {
if ((p&1) == 1) {
res = res * b;
}
b = b * b;
p >>= 1;
}
return res;
}
void init() {
Scanner sc = new Scanner(new BufferedInputStream(System.in));
int n = sc.nextInt();
long res = quick(2, n-1);
System.out.println(res);
}
}
public static void main(String[] args) throws IOException {
Solution s = new Solution();
s.init();
}
}
複雜度分析
- 時間複雜度:,
- 空間複雜度:,