A given number N, the output of less than 10 ^ N all integers

 

Speak up is relatively simple, from 0 to N traverse the output on the line, but if N is very large, involving integer overflow issue, it is clear that a full permutation problem, which is the output of N, on behalf of all the digital values ​​of the N-bit is 0 -9 make a full array, also we need to consider this is similar to the front 0001,0068,0977 0 when the output needs to remove.

Is a recursive basis of perfection permutation problem, of course, can not use recursion stack to solve, here is a recursive version of java.

public class Test {

    public static void recur(int[] arr, int index){
        if(index > arr.length - 1){
            // 输出
            //判断从第几位开始输出
            int start_id = 0;
            for(int j = 0; j < arr.length; j ++){
                if(arr[j] == 0){
                    start_id += 1;
                }
                else{
                    break;
                }
            }
            for(int j = start_id; j < arr.length; j ++){
                System.out.print(arr[j]);
            }
            System.out.println();
            return;
        }
        for(int i = 0; i <= 9; i ++){
            arr[index] = i;
            recur(arr, index + 1);
        }
        arr[index] = 0;

    }

    public static void main(String[] args){
        int[] arr = new int[4];
        recur(arr, 0);
    }
}

  

Guess you like

Origin www.cnblogs.com/zhouxiaosong/p/11402285.html