saurus2
Saurus2
saurus2
전체 방문자
오늘
어제
  • 분류 전체보기
    • 개발
      • AJAX
    • ML Ops
    • Profile
    • 음식점
    • 배낭여행
    • 컴퓨터공학
      • 알고리즘 공부
      • C++
      • Sever 스터디
      • Java spring
      • 알고리즘 _ 문제해결
      • 딥러닝
      • Java 정리
      • Python
      • LeetCode 1000
      • Machine Learning Study
      • Sign language Detection Pro..
      • LeetCode Solutions
    • 비콘
    • 데일리 리포트
    • 유학일기
      • 영어 공부
      • Daily
    • AI Master Degree
      • Data Mining
      • AI and Data engineering
      • Math Foundations for Decisi..
      • Natural Language Processing

블로그 메뉴

  • 홈
  • 태그
  • 미디어로그
  • 위치로그
  • 방명록

공지사항

인기 글

태그

  • 백준
  • 알고리즘문제해결
  • 알고리즘
  • DFS
  • LeetCode
  • 개발자 취업준비
  • Python
  • 문제해결능력
  • 딥러닝
  • 온라인저지
  • BFS
  • 취준
  • two pointer
  • 개발자
  • 취업준비
  • 리트코드
  • 딕셔너리
  • c++
  • 릿코드
  • 파이썬

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
saurus2

Saurus2

컴퓨터공학/LeetCode 1000

[LeetCode] 1155. Number of Dice Rolls With Target Sum

2022. 10. 4. 07:02

1155. Number of Dice Rolls With Target Sum

Medium

You have n dice and each die has k faces numbered from 1 to k.

Given three integers n, k, and target, return the number of possible ways (out of the kn total ways) to roll the dice so the sum of the face-up numbers equals target. Since the answer may be too large, return it modulo 109 + 7.

 

Example 1:

Input: n = 1, k = 6, target = 3
Output: 1
Explanation: You throw one die with 6 faces.
There is only one way to get a sum of 3.

Example 2:

Input: n = 2, k = 6, target = 7
Output: 6
Explanation: You throw two dice, each with 6 faces.
There are 6 ways to get a sum of 7: 1+6, 2+5, 3+4, 4+3, 5+2, 6+1.

Example 3:

Input: n = 30, k = 30, target = 500
Output: 222616187
Explanation: The answer must be returned modulo 109 + 7.

 

Constraints:

  • 1 <= n, k <= 30
  • 1 <= target <= 1000

문제 풀이

  • 주사위를 던질 수 있는 개수는 n, 주사위의 눈금은 k, 모든 주사위를 던저 합한 값이 target 일 조건의 갯수를 구해야한다.
  • Backtracking 으로 완전탐색을 시도하여 문제를 풀 수 있다. 
  • 하지만 n 의 갯수가 최대 30 이기 때문에, 그리고 k 값도 30 일 수 있어서 시간 초과가 날 수 있다. 
  • 재귀함수 호출시 브랜치가 30 이면 각 노드 레벨에서 30 개의 브랜치를 타고 들어가기 때문에, 30^30 까지 진행될 수 있다. 
  • 그래서 각 n 개의 주사위를 던졌을때 계산된 갯수를 메모이제이션을 활용하여 리턴해야한다. 
  • Bottom-up 으로 풀때, 종료 조건은 우선 n 개를 모두 던졌지만 target 에 도달했을때랑 도달하지 못했을때 리턴을 해준다. 
  • 그리고 가지치기로 해쉬 테이블에 n 번 던졌을때 합이 있다면 더 이상 재귀호출을 하지않고 이미 구해서 저장된 값을 리턴한다.
  • 해쉬 테이블을 사용하지 않고 @lru_cache 를 사용해도 무방하다.

소스코드

해쉬 테이블 사용

class Solution:
    def numRollsToTarget(self, n: int, k: int, target: int) -> int:
        hash_table = defaultdict()
        mod = 10**9 + 7
        def rec(n, t):
            if (n, t) in hash_table:
                return hash_table[(n, t)]
            
            if n == 0 and t != 0:
                return 0
            if n == 0 and t == 0:
                return 1
            
            total = 0
            for i in range(1, k + 1):
                total += rec(n - 1, t - i)
            hash_table[(n, t)] = total
            return total % mod
        return rec(n, target)

@lru_cache 사용

class Solution:
    def numRollsToTarget(self, n: int, k: int, target: int) -> int:
        mod = 10**9 + 7
        @lru_cache(maxsize=None)
        def rec(n, t):
            if n == 0 and t != 0:
                return 0
            if n == 0 and t == 0:
                return 1
            
            total = 0
            for i in range(1, k + 1):
                total += rec(n - 1, t - i)
            return total % mod
        return rec(n, target)
저작자표시 (새창열림)

'컴퓨터공학 > LeetCode 1000' 카테고리의 다른 글

[LeetCode] 531. Lonely Pixel I  (0) 2022.10.06
[LeetCode] 1578. Minimum Time to Make Rope Colorful  (0) 2022.10.05
[LeetCode] 91. Decode Ways  (0) 2022.10.04
[LeetCode] 218. The Skyline Problem  (0) 2022.10.01
[LeetCode] 658. Find K Closest Elements  (0) 2022.09.30
    '컴퓨터공학/LeetCode 1000' 카테고리의 다른 글
    • [LeetCode] 531. Lonely Pixel I
    • [LeetCode] 1578. Minimum Time to Make Rope Colorful
    • [LeetCode] 91. Decode Ways
    • [LeetCode] 218. The Skyline Problem
    saurus2
    saurus2
    Simple is Best

    티스토리툴바