数组A中给定可以使用的1~9的数,返回由A数组中的元素组成的小于n的最大数。例如A={1, 2, 4, 9},x=2533,返回2499

874 阅读1分钟

[字节面试题]数组A中给定可以使用的1~9的数,返回由A数组中的元素组成的小于n的最大数。例如A={1, 2, 4, 9},x=2533,返回2499

解决方案: 回溯

import java.util.Arrays;

public class Test {
    static int ans = 0;
    static int count = 0;

    public static void main(String[] args) {
        int x = 2533;
        int[] A = new int[]{1,2,4,9};
        Arrays.sort(A);
        int n = x == 0 ? 0 : 1;
        int t = x;
        while(t / 10 != 0){
            n++;
            t /= 10;
        }
        if(n == 0) System.out.println(-1);;
        backtrack(A, x, 0, n);
        System.out.println(ans);
    
    }

    static void backtrack(int[] A, int x,int res,  int n){
        if(count > n) return ;
        if(res < x) ans = Math.max(ans, res);    
        
        for(int i=A.length-1; i >= 0; i--){
            res = res * 10 + A[i];
            count++;
            backtrack(A, x, res, n);
            count--;
            res = (res - A[i]) / 10;
        }
    }
}

注:个人记录,代码可能没有考虑到所有情况