leetcode 打印从1到最大的n位数

    技术2022-07-10  146

    书上原题本想考的是大数问题,但是leetcode上要求的返回值是int,不可能出现当n过大时大数越界的问题, 失去了本题的意义。按大数问题处理,用string和递归来处理该问题。

    public class Solution { public int[] PrintNumbers(int n) { List<int> resList = new List<int>(); char[] bigNumber = new char[n]; DFS(0, n, ref bigNumber, resList); if(resList.Contains(0)) resList.Remove(0); return resList.ToArray(); } private void DFS(int n, int target, ref char[]bigNumber, List<int> resList) { if(n == target) { string s = new string(bigNumber); resList.Add(int.Parse(s)); return; } for(int i = 0 ; i < 10; i++) { bigNumber[n] = char.Parse( i.ToString() ); DFS(n + 1, target, ref bigNumber, resList); } } }

     

    Processed: 0.028, SQL: 9