前面面試華爲狀態不佳,而後就掛了,華爲不聊技術只聊人生,莫名其妙地沒有進二面,應該是水平不夠吧。等了好久,蘑菇街給了筆試機會。java
過久沒有作筆試題了,忽然來了一份筆試,想了好久,兩道題都沒有AC,還不知道有沒有面試機會,暫且記錄一下筆試題吧。都是寶貴的經驗!都是常規題目!面試
基本原理:好比輸入123,則1開頭,對[2,3]全排列,2開頭,對[1,3]全排列,3開頭,對[2,1]全排列。。。如此類推,構成一個樹。數組中全部的值都和第一個值交換後,在對第一個數組後面的數組進行全排列。注意考慮重複元素的情況,先對數組進行排序,若是先後值相同且前一個值被交換過,則跳過當前值。數組
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class NoPermutation{ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String s = scanner.nextLine(); char[] chars = s.toCharArray(); //char[] chars = new char[]{'a','c','c'}; Arrays.sort(chars); boolean[] booleans = new boolean[chars.length]; List<StringBuilder> stringBuilders = new ArrayList<>(); permute(chars,0,chars.length,stringBuilders,booleans); System.out.print(stringBuilders.toString()); } public static void swap(char[] chars,int i,int j){ char temp = chars[i]; chars[i] = chars[j]; chars[j] = temp; } public static void permute(char[] chars,int m,int n,List<StringBuilder> stringBuilders,boolean[] booleans){ if (m==n){ StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < n; i++) { stringBuilder.append(chars[i]); } stringBuilders.add(stringBuilder); return; } for (int i = m; i < n; i++) { if (i>0&&chars[i]==chars[i-1]&&!booleans[i-1]) continue; booleans[i] = true; swap(chars,i,m);//關鍵 permute(chars,m+1,n,stringBuilders,booleans); swap(chars,i,m); booleans[i] = false; } } }
基本原理:定義一個全爲1的數組mincandy,先從左往右遍歷rate,若是rate[i]>rate[i-1],則mincandy[i]=mincandy[i-1]+1,而後從右往左遍歷rate,若是rate[i]>rate[i+1]&&mincandy[i]<mincandy[i+1]+1,則mincandy[i] = mincandy[i+1]+1。app
import java.util.Arrays; import java.util.Scanner; public class Candy { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String in = scanner.nextLine(); String[] ratings = in.split(" "); System.out.print(mincandy(ratings)); } public static int mincandy(String[] ratings){ int[] rates = new int[ratings.length]; for (int i = 0; i < ratings.length; i++) { rates[i] = Integer.parseInt(ratings[i]); } int[] mincandy = new int[ratings.length]; Arrays.fill(mincandy,1); for (int i = 1; i < ratings.length; i++) { if (rates[i]>rates[i-1]){ mincandy[i] = mincandy[i-1]+1; } } int sum = mincandy[rates.length-1]; for (int i = rates.length-2; i >= 0 ; i--) { if (rates[i]>rates[i+1]&&mincandy[i]<mincandy[i+1]+1){ mincandy[i] = mincandy[i+1]+1; } sum+=mincandy[i]; } return sum; } }