Description:输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
import java.util.ArrayList;
import java.util.Arrays;
public class Solution {
String min = null;
public String PrintMinNumber(int[] a) {
int n = a.length;
ArrayList<String> list = new ArrayList<>();
if (n == 0) return "";
if (n == 1) return String.valueOf(a[0]);
boolean[] vis = new boolean[n];
backtrack(list, new ArrayList<Integer>(), vis, n, a);
return list.get(0);
}
public void backtrack(ArrayList<String> list, ArrayList<Integer> tmpList, boolean[] vis, int n, int[] a) {
if (tmpList.size() == n) {
String tmp = sum(tmpList);
if (min == null || tmp.compareTo(min) < 0) {
if (list.size() > 0) list.remove(0);
list.add(tmp);
min = tmp;
}
return ;
}
for (int i = 0; i < n; i++) if (!vis[i]) {
tmpList.add(a[i]);
vis[i] = true;
backtrack(list, tmpList, vis, n, a);
tmpList.remove(tmpList.size() - 1);
vis[i] = false;
}
}
public String sum(ArrayList<Integer> list) {
StringBuilder str = new StringBuilder();
for (Integer aa : list) {
str.append(aa);
}
return str.toString();
}
}