深搜即可,相當於在全排列裡找個滿足條件的
import java.util.*;public class text{public static int[] num=new int[1001];public static void dfs(int count,int sum,int now,int n){if(sum>n)return;if(sum==n){System.out.printf("%d=",n);for(int i=0;i<count-1;i++)System.out.printf("%d+",num[i]);System.out.printf("%d\n",num[count-1]);return;}if(now>=n) //要求分解的因子小於該數字return;for(int i=now;i<n;i++){num[count]=i; dfs(count+1,sum+i,i+1,n);}return;}public static void explode(int n){dfs(0,0,1,n);}public static void main(String args[]){Scanner reader=new Scanner(System.in);int t=reader.nextInt();explode(t);reader.close();}}
第二題:括弧匹配
類比一個棧即可
import java.util.*;public class text{public static char[] str=new char[100];public static char[] stack=new char[100];public static int judge(char str[],int len){int n=0;//棧的深度for(int i=0;i<len;i++){switch(str[i]){case '{': stack[n++]='{';break;case '[': stack[n++]='[';break;case '(': stack[n++]='(';break;case '}':if(n>=1&&stack[n-1]=='{'){n--;break;}elsereturn 0;case ']':if(n>=1&&stack[n-1]=='['){n--;break;}elsereturn 0;case ')':if(n>=1&&stack[n-1]=='('){n--;break;}elsereturn 0;}}if(n==0)return 1;return 0;}public static void main(String args[]){Scanner reader=new Scanner(System.in);String ss=reader.nextLine();reader.close();for(int i=0;i<ss.length();i++){str[i]=ss.charAt(i);}if(judge(str,ss.length())==1)System.out.println("YES");elseSystem.out.println("NO");}}
第三題計算19900101至某天的天數,然後按三天打漁兩天晒網,判斷這天在幹嘛
判斷是否是閏年即可
import java.util.*;public class text{public static int year,month,day;public static char[] ss=new char[8];public static int[] d=new int[]{0,31,28,31,30,31,30,31,31,30,31,30,31};public static void main(String args[]){Scanner reader=new Scanner(System.in);String str=reader.nextLine();reader.close();year=month=day=0;for(int i=0;i<8;i++)ss[i]=str.charAt(i);//字串轉為數字year=(ss[0]-'0')*1000+(ss[1]-'0')*100+(ss[2]-'0')*10+(ss[3]-'0');month=(ss[4]-'0')*10+(ss[5]-'0');day=(ss[6]-'0')*10+(ss[7]-'0');//System.out.println(year+" "+month+" "+day);int sum=0;for(int i=1990;i<year;i++){if((i%4==0)&&(i%100!=0)||(i%400==0))sum+=366;elsesum+=365;}for(int i=1;i<month;i++){sum+=d[i];}sum+=day;if(month>=3&&((year%4==0)&&(year%100!=0)||(year%400==0)))sum++;if(1<=(sum%5)&&(sum%5)<=3)System.out.printf("期間有%d天,該天在打魚\n",sum);elseSystem.out.printf("期間有%d天,該天在曬網\n",sum);}}