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);
		}
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章