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);
		}
	}
}
发布了72 篇原创文章 · 获赞 19 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_41022094/article/details/102184070