用dfs,先发m拆分放进list里面,递归时候再取出来 public class findMax { int max; public int findMaxNumber(int m , int n) { max = 0; List<Integer> list = new LinkedList<>(); while (m > 0) { list.add(0,m%10); m = m/10; } getMax(list,0,n,0); return 0; } private void getMax(List<Integer> list, int i, int n, int sum) { if (sum > max && i == list.size()) { max = sum; } for (int j = i; j < list.size(); j++) { int a = 0; for (int k = i; k <= j; k++) { a = a*10 + list.get(k); } if (sum + a > n) { break; } getMax(list, j+1, n, sum+a); } } }
/* 输入: 654122 111 输出: 110 */
我刚刚写的,不知道对不对。可以参考一下,把所有可能的分割情况都算了一遍…… import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { int n = in.nextInt(); int m = in.nextInt(); List<Integer> list = new ArrayList<>(); String s = String.valueOf(n); for(int i=0;i<s.length();i++){ list.add(s.charAt(i)-'0'); } List<Integer> l = new ArrayList<>(); fon(0,list,l,m); int min = -1; for(int i : l){ if(i>min) min = i; } System.out.println(min); } } public static void fon(int sum,List<Integer> list,List<Integer> l,int m){ if(list.size() == 0) l.add(sum); else{ int temp = list.get(0); while(sum+temp <= m){ list.remove(0); fon(sum+temp,new ArrayList<Integer>(list),l,m); if(list.size() == 0) break; else{ temp = temp*10 + list.get(0); } } } } }