美文网首页
Leetcode386-Lexicographical Numb

Leetcode386-Lexicographical Numb

作者: BlueSkyBlue | 来源:发表于2018-05-17 22:11 被阅读20次

题目:

Given an integer n, return 1 - n in lexicographical order.

For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9].

Please optimize your algorithm to use less time and space. The input size may be as large as 5,000,000.


思路:

由于之前做过相关的题目。原本以为这道题是很简单的字典序排序但是被这道题后面的那句话(Please optimize your algorithm to use less time and space.)打脸了。

这道题用到了非常巧妙的排序解法。我们可以通过组合数据的方式解决这道题。任何数据都是以[0, 9]开头的,由于此题的最小值是1,所以这个区间是[1, 9]。

之后是递归函数的设计,递归需要满足的第一个条件就是跳出,一旦咱们组合的数(target)大于输入的值n的时候就跳出递归。之后就是组数操作,设置一个循环,范围从0~10,之后target乘上10并加上循环的指数[0, 10]。在进行调用自身函数的操作。这是递归需要满足的第二个条件。


代码:

/**
     * Lexicographical Order
     * @param n
     * @return
     */
public List<Integer> lexicalOrder(int n) {
       List<Integer>result = new ArrayList<Integer>();
       for(int i=1;i<10;i++){
        recursive(result, i, n);
       }
       return result;
}
    
private void recursive(List<Integer> list, int target, int num){
    if(target>num){
        return;
    }
    list.add(target);
    for(int i=0;i<10;i++){
        recursive(list, target*10 + i, num);
    }
}

相关文章

  • Leetcode386-Lexicographical Numb

    题目: Given an integer n, return 1 - n in lexicographical o...

  • Numb

    最爱的是Linkin Park的Numb 今天突然看到报道说主唱Chester Bennington在加州洛杉矶的...

  • Numb

    19号晚上依然在熬夜,丧的妈都不认识。 醒来Chester Bennington自杀的消息挤爆热搜,主唱伤痛的过往...

  • numb

    在蓝白床上 写下killing time 印下的却是numb 痛苦逼我踌躇 回归快成了赌注 希望一直瞩目 却只徒留...

  • Numb

    Linkin Park,想起我大学用过的英文名字--crazy。 没有帷幕的舞台,空空得一清二楚瞧见身边的好友、同...

  • Numb

    生活以逼得我晕头转向 麻木不仁的心 波澜不惊的思绪 一天天的重复 我感觉的到 我离自己想成为的样子愈走愈远 这根本...

  • NUMB

    当查斯特起身说起“Good Goodbye”,世间再无林肯公园。 没人知道当年查斯特为何选择离开,我们在悲痛与不解...

  • comfortably numb

    Hello, is there anybody in there? Just nod if you can hea...

  • comfortably numb

    听哈佛大学幸福公开课的时候,被一个词深深地吸引,不得不感叹大家就是大家,能用语言如此精准地描绘出一批人人的生...

  • Numb—麻木

    Numb—麻木 这是一首震撼的摇滚歌曲 《NUMB》收录于 linkin park2003年的专辑Met...

网友评论

      本文标题:Leetcode386-Lexicographical Numb

      本文链接:https://www.haomeiwen.com/subject/ofwidftx.html