深度优先搜索DFS练习

例1:

Description:

现给定一个含有n个元素的数组A,要求:从这n个数中选择一些数,这些数的和恰好为k

Input:

多组测试数据。第一行为n(1<=n<=20) 第二行为n个整数,每个数的范围为(-10^8≤A[i]≤10^8) 第三行为整数k(-10^8≤k≤10^8).

Output:

如果能够达到目的,输出”Of course,I can!”; 否则输出”Sorry,I can’t!”.

Sample Input:

4

1 2 4 7

13

4

1 2 4 7

15

Sample Output:

Of course,I can!

Sorry,I can't!

代码:

import java.util.Scanner;

public class Main {
	static int y;
	static int v[] = new int[20], a[] = new int[20];
	static int n, k;

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while (sc.hasNext()) {
			n = sc.nextInt();
			for (int i = 0; i < n; i++)
				a[i] = sc.nextInt();
			k = sc.nextInt();
			y = 0;
			for (int i = 0; i < n; i++)
				v[i] = 0;
			DFS(0, 0);
			if (y == 1)
				System.out.println("Of course,I can");
			else
				System.out.println("Sorry,I can't!");
		}
	}
	
	private static int DFS(int i, int sum) {
		// TODO Auto-generated method stub
		if (i < n && v[i] == 0) {
			v[i] = 1;
			if (sum + a[i] == k) {
				y = 1;
				return y;
			} else if (sum + a[i] < k) {
				DFS(i + 1, sum);
				DFS(i + 1, sum + a[i]);
			} else
				DFS(i + 1, sum);
			v[i] = 0;
		}
		return y;
	}
}

 

例2:

Description:

问题很简单,给你n个正整数,求出这n个正整数中所有任选k个相乘后的和。

Input:

输入有两行,第一行是两个整数n和k,其中1<=k<=n<=10。接下去一行就是n个正整数,保证最后结果用long即可保存。

Output:

输出只有一个正整数,为最后的和。

Sample Input:

4 2

1 2 3 4

Sample Output:

35

代码:

import java.util.Scanner;

public class Main {
	static long sum;
	static int v[] = new int[20], a[] = new int[20];
	static int n, k;

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		k = sc.nextInt();
		for (int i = 0; i < n; i++)
			a[i] = sc.nextInt();
		DFS(0, 0, 1);
		System.out.println(sum);
	}

	private static void DFS(int i, int c, int s) {
		// TODO Auto-generated method stub
		if (c == k) {
			sum += s;
			return;
		}
		if (i >= n)
			return;
		if (v[i] == 0) {
			v[i] = 1;
			DFS(i + 1, c + 1, s * a[i]);
			DFS(i + 1, c, s);
			v[i] = 0;
		}
		return;
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值