【发布时间】:2017-01-04 18:25:53
【问题描述】:
我有一个包含 n 个整数数组(我们称之为数组)和一个数字 k 的向量。我必须找到一种方法来制作一个向量,我们称之为 Sol,其属性是所有元素的总和为 k,并且 Sol[i] 来自 Arrays[i]。 例如:
第一个是n,第二个是k,然后是数组。
输入:
3 10
1 2 3
2 5 7
4 6 8
控制台:
2 2 6
我可以简单地使用回溯,但是非常复杂。我试图制作一个从底部开始的算法,并为每个点结合下面的点,列出可能的解决方案,例如:
3 10
1 2 3
2 5 7
4 6 8
ex for:
8 < 10, viable solution
6 < 10, viable solution
4 < 10, viable solution
7 + 8 = 15 < 10 false never check this path again
7 + 6 = 13 < 10 false never check this path again
...
即使我这样做,在某些情况下也会非常复杂。我的目标是 O(m*k) 复杂度,其中 m 是所有输入数组的长度之和。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Vector;
public class Main {
static Vector<Vector<Integer>> Arrays;
static int Arrays_lenght;
static int sum;
public static void main(String[] args) throws FileNotFoundException
{
Scanner data_in = new Scanner(new File("data.in"));
Arrays_lenght = data_in.nextInt();
sum = data_in.nextInt();
Arrays = new Vector<>();
data_in.nextLine();
//read vectors
for(int i = 0; i < numar_vectori; i++)
{
String temp = data_in.nextLine();
Scanner _temp = new Scanner(temp);
Vector<Integer> temp_vector = new Vector<>();
while (_temp.hasNext()) {
temp_vector.add(_temp.nextInt());
}
Arrays.add(temp_vector);
}
Iterator<Vector<Integer>> itr = Arrays.iterator();
while (itr.hasNext())
System.out.printf("%s\n", itr.next().toString());
}
}
这是我在 java 中读取输入文件的代码。如何使 Sol 向量具有 O(m*k) 复杂度,其中 m 是所有输入数组的长度之和?
【问题讨论】:
-
你的问题是什么?
-
如何使 Sol 向量具有 O(m*k) 复杂度,其中 m 是所有输入数组的长度之和。抱歉,如果不清楚。我会修复我的帖子。
-
你考虑过动态规划吗?您将需要大小约为 k*n 的存储数组(取决于实现)
-
阅读它。不知道如何实施。一些伪代码的想法?