Algorithm

수들의 합 2 (백준 알고리즘 2003번)

OOOooOOoo·2019년 5월 28일·조회 3,869

1. 문제

https://www.acmicpc.net/problem/2003


2. 코드 #1

	public static void main(String[] args) {
		// int[] nums = { 1, 1, 1, 1 };
		int[] nums = { 1, 2, 3, 4, 2, 5, 3, 1, 1, 2 };
		int m = 5;
		int result = 0;
		

		for ( int i=0; i<nums.length; i++ ) {
			int thisSum = 0;
			for ( int j=i; j<nums.length; j++) {
				thisSum += nums[j];
				if ( thisSum == m ) {
					result++;
					break;
				}
			}
		}

		System.out.println("result="+result);
	}

 


3. 코드 #2

	public static void main(String[] args) {
		// int[] nums = { 1, 1, 1, 1 };
		int[] nums = { 1, 2, 3, 4, 2, 5, 3, 1, 1, 2 };
		int m = 5;
		int sum = 0;
		int result = 0;
		int i = 0;
		int j = 0;

		while (true) {
			if (sum >= m) {
				sum -= nums[i++];
			} else if (j == nums.length) {
				break;
			} else {
				sum += nums[j++];
			}

			if (sum == m) {
				System.out.println(i + "~" + j);
				result++;
			}
		}

		System.out.println("result=" + result);
	}

댓글 0

로그인 후 댓글을 남길 수 있습니다.

아직 댓글이 없습니다.