leetcode:Lexicographical Numbers

原创 2016年08月28日 14:36:07

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.

Subscribe to see which companies asked this question

给出一个数字n,列出这个数字 1- n内的字典顺序
发现了一个情况
我提交第一份递归代码的时候是没有通过的

public class Solution {
   public List<Integer> lexicalOrder(int n) {
            List<Integer> ans = new LinkedList<>();
            for(int i = 1; i < 10; ++i)
                order(n, i, ans);
            return ans;
    }

     public void order(int n, int base, List<Integer> list){
         if(base > n){
             return;
         }
         list.add(base);
         for(int i = 0; i < 10; ++i){
             order(n, base * 10 + i,list);
         }
     }
}

当改成static类变量的时候通过了

public class Solution {
   static List<Integer> ans = new LinkedList<>();
   public List<Integer> lexicalOrder(int n) {
        ans.clear();
        for(int i = 1; i < 10; ++i)
            order(n, i, ans);
        return ans;
    }

     public void order(int n, int base, List<Integer> list){
         if(base > n){
             return;
         }
         list.add(base);
         for(int i = 0; i < 10; ++i){
             order(n, base * 10 + i, list);
         }
     }
}
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

LeetCode—386. Lexicographical Numbers

386. Lexicographical Numbers Total Accepted: 1486Total Submissions: 5876Difficulty: Medium...

leetcode_middle_44_386. Lexicographical Numbers

题意: 给一个数n,按照字典顺序返回1-n。 分析: 什么是字典顺序呢?观察例子,分析是按位比较,先比较最高位。 我们按照人脑思维,是应该怎么选出排序呢?首先1,10,11,12......

LeetCode 2. Add Two Numbers(Java)

原题: You are given two non-empty linked lists representing two non-negative integers. The digits are...

Leetcode 129. Sum Root to Leaf Numbers (Medium) (cpp)

Leetcode 129. Sum Root to Leaf Numbers (Medium) (cpp)

LeetCode(2)--Add Two Numbers

You are given two non-empty linked lists representing two non-negative integers. The digits are stor...

LeetCode: Add Two Numbers

LeetCode: Add Two NumbersYou are given two linked lists representing two non-negative numbers. The d...

[leetcode] 165.Compare Version Numbers

题目: Compare two version numbers version1 and version2. If version1 > version2 return 1, if version...

LeetCode002 Add Two Numbers

详细见:leetcode.com/problems/add-two-numbers/ 说明:链表操作+进位 Java Solution: github package leetcode; /*...

2. Add Two Numbers LeetCode题解

题目描述: You are given two non-empty linked lists representing two non-negative integers. The digits...

LeetCode Problem:Add Two Numbers

Problem 2:Two Numbers You are given two linked lists representing two non-negative numbers....
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)