[LeetCode386] Lexicographical Numbers(n 이내의 숫자는 사전순으로 출력)

986 단어 LeetCode
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.
 : ( )
class Solution {
public:
    vector lexicalOrder(int n) {
        vector ans(n);
		for(int i=1; i<=9; i++)
		{
			if(i>n) break;
			solve(i, n, ans);
		}
		return ans;
    }
	void solve(int cur, int n, vector& ans)
	{
		ans.push_back(cur);
		for(int i=0; i<=9; i++)
		{
			int tmp=cur*10+i;
			if(tmp>n) return ;
			solve(tmp, n, ans);
		}
	}
};
 : ( )
class Solution {
public:
    vector lexicalOrder(int n) {
        vector ans;
		int cur=1;
        for(int i=0; i=n) cur/=10;
                cur+=1;
                while(cur%10==0) cur/=10;
            }
        }
        return ans;
    }
};

좋은 웹페이지 즐겨찾기