返回所有长度为 n 且满足其每两个连续位上的数字之间的差的绝对值为 k 的 非负整数 。 请注意,除了 数字 0
本身之外,答案中的每个数字都 不能 有前导零。例如,01 有一个前导零,所以是无效的;但 0 是有效的。 你可以按 任何顺序 返回答案。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/numbers-with-same-consecutive-differences
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
int *ret = NULL;
int num = 0;
void backtrack(int n, int k, int *size, int index,int value)
{
if(index == n)
{
num = num * 10 + value;
ret[(*size)++] = num;
return;
}
num = num * 10 + value;
int temp[2] = {value - k, value + k};
for(int i = 0; i < 2; i++)
{
if(i != 0 && k == 0) break; //前后一样就只需要一次即可
if(temp[i] >= 0 && temp[i] < 10) //计算结果需为0~9
{
backtrack(n, k, size, index+1, temp[i]);
num = (num - temp[i]) / 10;
}
}
}
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* numsSameConsecDiff(int n, int k, int* returnSize){
ret = (int*)malloc(sizeof(int) * 2000);
*returnSize = 0;
num = 0;
for(int i = 1; i < 10; i++)
{
if((i >= 1 && i <= 9 - k) || (i >= k && i <= 9)) //限制进入的首位数字
{
num = 0;
backtrack(n, k, returnSize, 1, i);
}
}
return ret;
}
思路:回溯算法