NC362. 字典序排列
描述
示例1
输入:
5
输出:
[1,2,3,4,5]
示例2
输入:
10
输出:
[1,10,2,3,4,5,6,7,8,9]
C 解法, 执行用时: 14ms, 内存消耗: 1292KB, 提交时间: 2022-04-07
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param n int整型 * @return int整型一维数组 * @return int* returnSize 返回数组行数 * * C语言声明定义全局变量请加上static,防止重复定义 */ void dfs(int n, int sum, int *ans, int *returnSize) { int base = sum * 10; if (base <= n) { for (int i = 0; i <= 9; ++i) { sum = base + i; if (sum <= n && sum != 0) { ans[(*returnSize)++] = sum; dfs(n, sum, ans, returnSize); } } } } int* orderArray(int n, int* returnSize ) { // write code here int *ans = (int *)malloc(sizeof(int) * 100000); *returnSize = 0; dfs(n, 0, ans, returnSize); return ans; }
C 解法, 执行用时: 16ms, 内存消耗: 1308KB, 提交时间: 2022-07-08
void back(int n, int sum, int* z, int* returnSize) { int a = sum * 10; if (a <= n) { for (int i = 0; i <= 9; ++i) { sum = a + i; if (sum <= n && sum != 0) { z[(*returnSize)++] = sum; back(n, sum, z, returnSize); } } } } int* orderArray(int n, int* returnSize ) { int* z = (int*)malloc(sizeof(int) * 100000); *returnSize = 0; back(n, 0, z, returnSize); return z; }
C++ 解法, 执行用时: 16ms, 内存消耗: 1328KB, 提交时间: 2022-06-01
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param n int整型 * @return int整型vector */ vector<int> orderArray(int n) { // write code here vector<int>res(n); int tmp = 1; for (int i = 0; i < n; i++) { res[i] = tmp; if (tmp * 10 <= n) { tmp *= 10; } else { while (tmp % 10 == 9 || tmp + 1 > n) { tmp /= 10; } tmp++; } } return res; } };
C 解法, 执行用时: 17ms, 内存消耗: 1312KB, 提交时间: 2022-04-05
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param n int整型 * @return int整型一维数组 * @return int* returnSize 返回数组行数 * * C语言声明定义全局变量请加上static,防止重复定义 */ void dfs(int n, int sum, int *retBuf, int *returnSize) { int base = sum * 10; if (base <= n) { for (int i = 0; i <= 9; i++) { sum = base + i; if (sum <= n && sum != 0) { retBuf[*returnSize] = sum; (*returnSize) += 1; dfs(n, sum, retBuf, returnSize); } } } } int* orderArray(int n, int* returnSize ) { // write code here int *retBuf = malloc(100005 * sizeof(int)); *returnSize = 0; dfs(n, 0, retBuf, returnSize); return retBuf; }
C++ 解法, 执行用时: 17ms, 内存消耗: 1412KB, 提交时间: 2022-07-27
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param n int整型 * @return int整型vector */ vector<int> orderArray(int n) { // write code here vector<int> res(n); int k = 1; for (int i = 0; i < n; i ++) { res[i] = k; if(k * 10 <= n) { k *= 10; } else { while(k % 10 == 9 || k == n) k /= 10; k ++; } } return res; } };