全排列,使用treeSet,长度一定的情况下,自然序排第一个的就是最小的。
public String PrintMinNumber(int [] numbers) {
if(null == numbers || numbers.length == 0){
return "";
}
TreeSet<String> treeSet = new TreeSet();
perm(numbers,0,treeSet);
return treeSet.first();
}
public void perm(int[] nums,int index,TreeSet<String> result){
if(index == nums.length-1){
StringBuilder temp = new StringBuilder();
for (int i = 0; i < nums.length; i++) {
temp.append(nums[i]);
}
result.add(new String(temp));
return;
}
for(int i = index;i<nums.length;i++){
if(i == index || nums[index] != nums[i]){
swap(nums,i,index);
perm(nums,index+1,result);
swap(nums,i,index);
}
}
}
public void swap(int[] nums,int i,int j){
if( i == j){
return;
}
nums[i] = nums[i] + nums[j];
nums[j] = nums[i] - nums[j];
nums[i] = nums[i] - nums[j];
}
网友评论