面试题目:一个桶中有12斤油,要求倒出6斤,可现在另外只有两个桶,分别可装8斤与5斤,请问应如何来倒?

蒲志斌 2019-08-12 12:33:00
面试题目:一个桶中有12斤油,要求倒出6斤,可现在另外只有两个桶,分别可装8斤与5斤,请问应如何来倒?(急啊) 求助各位高人:分油算法:一个桶中有12斤油,要求倒出6斤,可现在另外只有两个桶,分别可装8斤与5斤,请问应如何来倒? 补充:这里的12,6,8,5都是变量,应该可以自己设置,输出是每一次分油的步骤。 ------解决方案-------------------- 加入了过程描述 C# code public Form1() { InitializeComponent(); //瓶子的实际容量 int[] bottlesRealityNum = { 12, 0, 0 }; falloil(ref bottlesRealityNum); MessageBox.Show(string.Format("b1:{0} b2:{1} b3:{2}", bottlesRealityNum[0], bottlesRealityNum[1], bottlesRealityNum[2])); } private void falloil(ref int[] source) { //瓶子的额定容量 int[] bottlesRating = { 12, 8, 5 }; if (source[0] != 6) { int temp = source[0]; source[0] = source[0] - bottlesRating[1]; if (source[0] < 0) { source[0] = 0; source[1] = temp; } else { { return; } }
...全文
216 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
蒲志斌 2019-09-04
  • 打赏
  • 举报
回复
引用 3 楼 河边放牛娃 的回复:
这个有点简单额,1.把8斤桶装满倒入5斤将5斤倒满,然后8斤桶还剩3斤。
2.将5斤桶导入原桶中,在将8斤中的3斤导入5斤桶,5斤桶就还差两斤满。
3.将8斤桶装满然后导入5斤直到倒满,剩余就是2斤了

程序都晓得结果了就直接输出就行了,时间复杂度还最优,每次循环直接输出 12 0 0 => 4 8 0 => 4 3 5=>9 3 0=>9 0 3=>1 8 3=>1 6 5
厉害
蒲志斌 2019-09-04
  • 打赏
  • 举报
回复
引用 1 楼 maradona1984 的回复:
12 => 4 + 8 + 0 => 4 + 3 + 5 =>9+ 3+0=>9+0+3=>1+8+3=>1+6+5 如果要用程序写出来就麻烦了,得想想
厉害哥
河边放牛娃 2019-08-13
  • 打赏
  • 举报
回复
这个有点简单额,1.把8斤桶装满倒入5斤将5斤倒满,然后8斤桶还剩3斤。
2.将5斤桶导入原桶中,在将8斤中的3斤导入5斤桶,5斤桶就还差两斤满。
3.将8斤桶装满然后导入5斤直到倒满,剩余就是2斤了

程序都晓得结果了就直接输出就行了,时间复杂度还最优,每次循环直接输出 12 0 0 => 4 8 0 => 4 3 5=>9 3 0=>9 0 3=>1 8 3=>1 6 5
maradona1984 2019-08-12
  • 打赏
  • 举报
回复
时间复杂度什么的我就懒得考虑了

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

public class Solution4 {

	int[] m = new int[] { 12, 8, 5 };
	int[] t = new int[] { 6, 6, 0 };
	Set<String> set = new HashSet<>();

	public void test(int[] c, String path) {
		String cStr = String.format("%s+%s+%s", c[0], c[1], c[2]);
		if (set.contains(cStr)) {
			return;
		}
		path = path + "=>" + cStr;
		String tStr = String.format("%s+%s+%s", t[0], t[1], t[2]);
		if (tStr.equals(cStr)) {
			System.out.println(path);
			return;
		}
		set.add(cStr);
		for (int i = 0; i < m.length; i++) {
			for (int j = 0; j < m.length; j++) {
				if (i == j) {
					continue;
				}
				if (c[j] == m[j]) {
					continue;
				}
				int[] temp = new int[c.length];
				System.arraycopy(c, 0, temp, 0, c.length);
				int swap = Math.min(m[j] - temp[j], temp[i]);
				temp[i] = temp[i] - swap;
				temp[j] = temp[j] + swap;
				test(temp, path);
			}
		}
	}

	public static void main(String[] args) {
		int[] c = new int[] { 12, 0, 0 };
		String path = "开始";
		new Solution4().test(c, path);
	}
}
maradona1984 2019-08-12
  • 打赏
  • 举报
回复
12 => 4 + 8 + 0 => 4 + 3 + 5 =>9+ 3+0=>9+0+3=>1+8+3=>1+6+5 如果要用程序写出来就麻烦了,得想想

51,397

社区成员

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

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