試題 算法訓練 擺動序列
資源限制
時間限制:1.0s 內存限制:512.0MB
問題描述
如果一個序列滿足下面的性質,我們就將它稱爲擺動序列:
1. 序列中的所有數都是不大於k的正整數;
2. 序列中至少有兩個數。
3. 序列中的數兩兩不相等;
4. 如果第i – 1個數比第i – 2個數大,則第i個數比第i – 2個數小;如果第i – 1個數比第i – 2個數小,則第i個數比第i – 2個數大。
比如,當k = 3時,有下面幾個這樣的序列:
1 2
1 3
2 1
2 1 3
2 3
2 3 1
3 1
3 2
一共有8種,給定k,請求出滿足上面要求的序列的個數。
輸入格式
輸入包含了一個整數k。(k<=20)
輸出格式
輸出一個整數,表示滿足要求的序列個數。
樣例輸入
3
樣例輸出
8
//解題思路:先給排列指定長度得出多少排序方法,然後在通過循環增加長度計算出總排序方法
package Main;
import java.util.Scanner;
public class Main {
//count 用於接收返回的不同個數
static int count=0;
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int m=sc.nextInt();
int[] as=new int[m];
//循環改變i來改變每次排序爲i的長度;
for (int i = 2; i <=m; i++) {
//m爲輸入的數(最大長度和排序數據範圍爲0~m),i爲判斷排序數字長度爲i個,
//as傳入一個方法用於獲取和判斷排序中每個位置的數,0 爲獲取排序長度的第(0+1)個數
Nums(m, i, as, 0);
}
System.out.print(count);
sc.close();
}
public static void Nums(int m,int le,int[] aa,int cc) {
//當排序達到指定長度時進行總數加1
if(cc==le) {
count++;
return;
}
int[] ss=aa;
for (int j = 1; j <=m; j++) {
//判斷排序中數字j在前面中是否出現或滿足題中大小排列不(aa中存放前cc個數字)
if(Boolshu(cc,j,aa)) {
ss[cc]=j;
int cou=cc+1;
Nums(m, le, ss,cou );
}
}
}
public static Boolean Boolshu(int co,int num,int[] aa) {
//判斷co前的數是否和num有一樣的,
//如果一樣則num不滿足題中要求的不重複性;
for (int i = 0; i <co ; i++) {
if(aa[i]==num) {
return false;
}
}
//判斷num是否滿足題中要求的大小排序;當co數小於2是,
//則不需要判斷(因爲前二個數是可以隨便排列,不需要區分大小寫)
if(co>=2) {
if(aa[co-2]>aa[co-1]) {
if(num>aa[co-2]) {
return true;
}
else {
return false;
}
}else {
if(num<aa[co-2]) {
return true;
}
else {
return false;
}
}
}
return true;
}
}