题解 | #把数组排成最小的数#
把数组排成最小的数
http://www.nowcoder.com/practice/8fecd3f8ba334add803bf2a06af1b993
思路:
1.套用之前的全排列方法,递归得到每种字符串
2.字符串转数值,取尝试更新最小值
3.返回记录的最小值
踩坑:
1.字符串太大,用int long double装不下
2.学会了用大数类 BigInter 构造时直接收入字符串
3.大数之间比较 用 x1.compareTo(x2)
import java.util.ArrayList; import java.math.BigInteger; public class Solution { static BigInteger min=new BigInteger("99999999999999999999999999"); public String PrintMinNumber(int [] numbers) { //套用之前做过的字符串全排列,得到结果后,尝试更新最小数记录 if(numbers.length==0){ return ""; } //把数组转化为ArryList able ArrayList able = new ArrayList(); for (int i = 0; i <=numbers.length-1 ; i++) { able.add(numbers[i]+""); } //开一个空的起始StringBuffer StringBuffer start=new StringBuffer(); //前者表示当前字符串,后者表示剩余可用字符集 fun(start,able); String result=min+""; return result; } public void fun(StringBuffer result,ArrayList able){ //接收当前字符串 开res副本接收result、able1接收able,且以便回溯 StringBuffer res=new StringBuffer(result); ArrayList able1=new ArrayList(able); //如果可用数组为空 if(able.size()==0){ //尝试更新最小树记录 BigInteger num=new BigInteger(res.toString()); if(num.compareTo(min) < 0){ min=num; }; } if(able.size()!=0) { //从可用字符集中取一个加到当前字符串 for (int i = 0; i <=able.size()-1 ; i++){ res.append(able.get(i)); able1.remove(i); fun(res, able1); //这里要回溯,恢复到刚传入的result和able值 able1=new ArrayList(able); res=new StringBuffer(result); } } } }