最近我遇到了这样一个问题:
假设你有一个int N,你也有一个int [],这个数组中的每个元素只能使用一次.我们需要设计一个算法,通过添加这些数字来获得1到N,最后返回我们需要添加的最少数字.
例如:
N = 6, array is [1,3]
1 : we already have.
2 : we need to add it to the array.
3 : we can get it by doing 1 + 2.
4: 1 + 3.
5 : 2 + 3.
6 : 1 + 2 + 3.
So we just need to add 2 to our array and finally we return 1.
Run Code Online (Sandbox Code Playgroud)
我正在考虑使用DFS解决这个问题.你有更好的解决方案吗?谢谢!
我尝试了下面的代码,但它没有给我正确的答案。
这是问题陈述。
假设您有一个二维网格。每个点要么是陆地,要么是水。还有一个起点和一个目标。
现在有打开门的钥匙。每把钥匙对应一扇门。
实现一个函数,使用地块、钥匙和打开的门返回从起点到目标的最短路径。
数据表示
地图将作为字符串数组传递。
地图可以具有以下图块。
0 = Water1 = Land2 = Start3 = Goaluppercase = doorlowercase = key网格可以是这样的:
Run Code Online (Sandbox Code Playgroud){{'0', '2', '1', '1', '1'}, {'0', '1', '0', '0', '1'}, {'0', '0', '0', '0', '1'}, {'0', '0', 'A', '0', '1'}, {'1', '1', 'a', '1', '1'}, {'1', 'b', '0', '0', 'B'}, {'1', '1', '0', '0', '1'}, {'0', '1', '0', '0', '3'}};所以最短路径应该是:01->02->03->04->14->24->34->44->43->42->41->51->41->42->43 ->44->54->64->74
我的代码如下:
public class shortestPath {
static int shortest = Integer.MAX_VALUE;
static …Run Code Online (Sandbox Code Playgroud)