leetcode10场双周赛-步进数 (搜索、dfs)

如果一个整数上的每一位数字与其相邻位上的数字的绝对差都是 1,那么这个数就是一个「步进数」。

例如,321 是一个步进数,而 421 不是。

给你两个整数,low 和 high,请你找出在 [low, high] 范围内的所有步进数,并返回 排序后 的结果。

示例:

输入:low = 0, high = 21
输出:[0,1,2,3,4,5,6,7,8,9,10,12,21]

提示:

0 <= low <= high <= 2 * 10^9

题目链接(leetcode)

思路:
如果直接用for循环跑的话,9次方分分钟超时,我们可以直接dfs去取拼凑所有的步进数 ,然后检查是否在low和high范围之间,注意数字可能会超,直接用long。

参考代码:

class Solution {
    
   public List<Integer> countSteppingNumbers(int low, int high) 
    {
    	List<Integer> ans=new ArrayList<Integer>();
    	List<Long> al=new ArrayList<Long>();
    	int min=(low+"").length();
    	int max=(high+"").length();
    	dfs(al, low, high, 0, 0);
    	for(int i=min;i<=max;i++)
    		for(int j=1;j<=9;j++)
    			dfs(al,low,high,i-1,j);
    	for(Long in:al)
    		ans.add(Integer.parseInt(in+""));
    	return ans;
    }
    
    private void dfs(List<Long> al,int low, int high, int k, long s) 
    {
		if(k==0)
		{
			if(s>=low&&s<=high)
				al.add(s);
			return;
		}
		if(s%10-1>=0)
		{
			long n=s%10-1;
			dfs(al,low, high, k-1, s*10+n);
		}
		if(s%10+1<=9)
		{
			long n=s%10+1;
			dfs(al,low, high, k-1, s*10+n);
		}
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值