문제 풀기/C#

85. 연속 부분 수열 합의 개수

kagan-draca 2025. 3. 4. 23:16

기본 틀 :

using System;

public class Solution {
    public int solution(int[] elements) {
        int answer = 0;
        return answer;
    }
}

 

중복이 없는 배열을 구성해야 되기 때문에 HashSet을 선언해줬다.

 

그리고 elements를 회전시켜야 하기 때문에 List를 선언하여 elements의 요소를 넣어줬다.

 

반복문으로 합을 구할 때 마다 hashSet에 추가하여 중복이 없는 요소를 저장할 수 있도록 만들어줬다.

(hashSet에 중복이 있을 경우 저장을 하지 않기 때문)

 

마지막으로 다음 반복으로 넘어갈 때 list[0]으로 index가 0인 요소를 temp에 저장하고

 

RemoveAt(0)으로 list의 index 0인 요소를 제거 후

 

list.Add(temp)로 index의 마지막 위치에 추가해줘서

 

순환 구조를 만들어줬다.

 

using System;
using System.Linq;
using System.Collections.Generic;

public class Solution {
    public int solution(int[] elements) {
        HashSet<int> hashSet = new HashSet<int>();
        List<int> list = new List<int>(elements);
        
        for(int i = 0; i < list.Count; i++)
        {
            int sum = 0;
            for(int j = 0; j < list.Count; j++)
            {
                sum += list[j];
                hashSet.Add(sum);
            }
            int temp = list[0];
            list.RemoveAt(0);
            list.Add(temp);
        }
        
        return hashSet.Count;
    }
}