인덱스가 오름차순으로 정렬되도록 주어진 합계를 갖는 하위 배열의 개수 (Count of sub-arrays with a given sum such that the indices are in ascending order)


문제 설명

인덱스가 오름차순으로 정렬되도록 주어진 합계를 갖는 하위 배열의 개수 (Count of sub‑arrays with a given sum such that the indices are in ascending order)

주어진 배열에서 인덱스가 오름차순이 되도록 주어진 합계로 하위 배열의 수를 계산합니다(연속적일 필요는 없지만 배열 요소의 인덱스는 오름차순이어야 합니다. )

예: 배열 ‑ {1 2 3 4 5}, Sum ‑ 5 그러면 인덱스가 오름차순(1 <4)이므로 {1,4}도 유효한 하위 배열입니다. 기타는 {2,3} 등입니다.

참고 ‑ 이 질문은 하위 배열의 개수에 대한 질문과 매우 유사한 것처럼 보이지만 인덱스가 오름차순인 경우 더 복잡해집니다. 더 많은 값이 있으므로 주문하십시오. 누군가에게 동일한 의사 코드를 공유하고 가능하지 않은 경우 논리를 공유해 달라고 요청합니다.


참조 솔루션

방법 1:

This problem is equivalent to counting the number of subsequences that sum to sum. Saying the indices have to be ascending doesn't really mean anything, as long as you don't have repeating indices. Then the problem can be solved with a knapsack‑esque dynamic programming approach.

Define dp[N+1][sum+1] to store, at dp[i][j] the number of subsequences of the array up to (but not including) index i that sum to j. Python code is as follows:

N = 10
sum = 10
arr = [1,2,3,4,5,1,2,3,4,5]

dp = [[0 for x in range(sum+1)] for x in range(N+1)]
dp[0][0] = 1  # base case; one way to achieve a sum of 0 taking 0 elements
for i in range(N):
    for j in range(sum+1):
        if j + arr[i] <= sum:
            dp[i+1][j+arr[i]] += dp[i][j]
        dp[i+1][j] += dp[i][j]

print dp[N][sum]

(by gamerrk1004aeternalis1)

참조 문서

  1. Count of sub‑arrays with a given sum such that the indices are in ascending order (CC BY‑SA 2.5/3.0/4.0)

#dynamic-programming #arrays #sub-array






관련 질문

나머지 숫자의 xor가 0인 부분 집합의 수를 찾습니다. (Find number of subsets, that xor of remaining numbers equals to 0)

재귀 대신 동적 프로그래밍을 사용하여 가장 큰 공통 접미사(자바스크립트) 찾기 (Use dynamic programming instead of recursion to find largest common suffix (javascript))

제거 방법 : java.lang.OutOfMemoryError (how to remove : java.lang.OutOfMemoryError)

가장 효율적인 좌석 배치 (Most efficient seating arrangement)

aglorithm의 복잡성을 가진 춤 (A dance with an aglorithm's complexity)

장애물이 있는 처음부터 끝까지 경로의 수를 계산합니다. (Count the number of paths from start to end with obstacles)

직사각형 필드 내에서 다양한 크기의 직사각형을 효율적으로 배치 (Efficient placement of variable size rectangles within a rectangular field)

기차 또는 버스를 이용할 수 있는 도시 간 최단 경로 DYNAMIC PROGRAMMING (Shortest path between cities that you can use either train or bus DYNAMIC PROGRAMMING)

인덱스가 오름차순으로 정렬되도록 주어진 합계를 갖는 하위 배열의 개수 (Count of sub-arrays with a given sum such that the indices are in ascending order)

2차원 배열의 경로 수 계산(그리드 Traveller) (Count number of paths on 2d-array (grid Traveller))

n개의 볼과 m개의 빈이 주어지고 각 빈이 특정 용량을 가질 때, 몇 개의 조합이 있습니까? (Given n balls and m bins, each bin with a certain capacity, how many combinations are there?)

재귀 호출을 메모할 때 엄청난 효율성 차이 (Drastic efficiency difference when memoizing recursive calls)







코멘트