파비의 매일매일 공부기록

Today's Challenge 본문

Problem Solving/LeetCode

Today's Challenge

fabichoi 2022. 9. 3. 23:45

https://leetcode.com/problems/numbers-with-same-consecutive-differences/

 

Numbers With Same Consecutive Differences - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

요즘에 DFS/BFS 문제가 주로 나오는 듯.

class Solution:
    def numsSameConsecDiff(self, n: int, k: int) -> List[int]:
        if n == 1:
            return [i for i in range(10)]
        
        ans = []
        
        def dfs(n, num):
            if n == 0:
                return ans.append(num)
            
            tail_digit = num % 10
            
            next_digits = set([tail_digit + k, tail_digit - k])
            
            for next_digit in next_digits:
                if 0 <= next_digit < 10:
                    new_num = num * 10 + next_digit
                    dfs(n-1, new_num)
        
        for num in range(1, 10):
            dfs(n-1, num)
            
        return list(ans)
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

Today's Challenge  (0) 2022.09.05
Today's Challenge  (0) 2022.09.04
Today's Challenge  (0) 2022.09.02
Today's Challenge  (0) 2022.09.01
Today's Challenge  (0) 2022.08.31
Comments