Java面试题求解!!!技术大牛看过来啊!

我是好吃的大西瓜 2014-04-30 05:49:40
在A,B两个城市之间设有N个路站(如下图中的S1,且N<100),城市与路站之间、路站和路站之间各有若干条路段(各路段数≤20,且每条路段上的距离均为一个整数)。
A,B的一条通路是指:从A出发,可经过任一路段到达S1,再从S1出发经过任一路段,…最后到达B。通路上路段距离之和称为通路距离(最大距离≤1000)。当所有的路段距离给出之后,求出所有不同距离的通路个数(相同距离仅记一次)。
例如:下图所示是当N=1时的情况:


原题在这,http://student.csdn.net/mcd/topic/235300/760973
...全文
347 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
Magical茏 2014-05-01
  • 打赏
  • 举报
回复
早上躺床上想到的一种迭代算法,
import java.util.HashSet;

public class TestNode1 {

	public static void main(String[] args) {
		int[][] distance = { { 5, 7, 4 }, { 6, 5 } };
		HashSet<Integer> setG = new HashSet<Integer>();

		for (int i = 0; i < distance.length; i++) {
			HashSet<Integer> temp = new HashSet<Integer>();
			temp.addAll(setG);
			setG.clear();
			for (int dd : distance[i]) {
				if (i == 0) {
					setG.add(dd);
				}
				for (int d : temp) {
					setG.add(d + dd);
				}
			}
		}

		System.out.println(setG);
	}
}
Magical茏 2014-04-30
  • 打赏
  • 举报
回复
当所有的路段距离给出之后,求出所有不同距离的通路个数(相同距离仅记一次)

这是其他稍复杂的一个例子来验证:


输出的结果是:

[13, 14, 15, 17, 16, 19, 18, 21, 20, 23, 22, 25, 24, 27, 26, 29, 28, 30]




import java.util.HashSet;
import java.util.Set;

public class TestNode1 {
static Set setG = new HashSet();// 用来装不同的 可行的 通路长度

public static void main(String[] args) {
int[] d4 = { 8, 4, 3 };
int[] d3 = { 1, 2 };
int[] d2 = { 10, 9, 8, 4 };
int[] d1 = { 5, 8, 10 };
Node n5 = new Node(null, null);// 终点
Node n4 = new Node(d4, n5);
Node n3 = new Node(d3, n4);
Node n2 = new Node(d2, n3);
Node n1 = new Node(d1, n2);

search(n1, n3, 0);
System.out.println(setG);// 输出可行的通路长度
}

static void search(Node start, Node end, int dis) {
if (start.next != null) {
for (int distance : start.distanceToNext) {
int temp = dis + distance;
search(start.next, end, temp);
}
} else {
setG.add(dis);
}
}

}

class Node {
int[] distanceToNext;// 到下一个节点的各个距离
Node next;// 下一个节点

public Node(int[] d, Node next) {
distanceToNext = d;
this.next = next;
}

}
Magical茏 2014-04-30
  • 打赏
  • 举报
回复
import java.util.HashSet;
import java.util.Set;

public class TestNode {
	static Set setG = new HashSet();// 用来装不同的 可行的 通路长度

	public static void main(String[] args) {
		int[] d1 = { 5, 7, 4 };
		int[] d2 = { 5, 6 };
		Node n3 = new Node(null, null);//终点
		Node n2 = new Node(d2, n3);
		Node n1 = new Node(d1, n2);

		search(n1, n3, 0);
		System.out.println(setG);// 输出可行的通路长度
	}

	static void search(Node start, Node end, int dis) {
		if (start.next != null) {
			for (int distance : start.distanceToNext) {
				int temp = dis + distance;
				search(start.next, end, temp);
			}
		} else {
			setG.add(dis);
		}
	}

}

class Node {
	int[] distanceToNext;// 到下一个节点的各个距离
	Node next;//下一个节点

	public Node(int[] d, Node next) {
		distanceToNext = d;
		this.next = next;
	}

}

50,530

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧