【回溯】B048_LQ_李白打酒(暴搜)

一、Problem

话说大诗人李白,一生好饮。幸好他从不开车。一天,他提着酒壶,从家里出来,酒壶中有酒2斗。他边走边唱:

无事街上走,提壶去打酒。
逢店加一倍,遇花喝一斗。

这一路上,他一共遇到店5次,遇到花10次,已知最后一次遇到的是花,他正好把酒喝光了。

请你计算李白遇到店和花的次序,可以把遇店记为a,遇花记为b。则:babaabbabbabbbb 就是合理的次序。像这样的答案一共有多少呢?请你计算出所有可能方案的个数(包含题目给出的)。

注意:通过浏览器提交答案。答案是个整数。不要书写任何多余的内容。

14

二、Solution

方法一:dfs

  • a 表示到店次数,b 表示遇花的次数。
  • 当 a = 5 && b = 10 时,如果路径 s 最后一位是否为桃花 'b',找到一个答案。
import java.util.*;
import java.math.*;
import java.io.*;
public class Main{
	static class Solution {
		int A = 5, B = 10, res;
		void dfs(int a, int b, int c, String s) {
		    if (a > A || b > B)
		        return;
			if (a == A && b == B) {
				if (c == 0 && s.charAt(s.length()-1) == 'b')
				    res++;
				return;
			}
			dfs(a+1, b, 2*c, s+"a");
			dfs(a, b+1, c-1, s+"b");
		}
		void init() {
			Scanner sc = new Scanner(new BufferedInputStream(System.in));
			BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out));
			dfs(0, 0, 2, "");
			System.out.println(res);
		}
	}
    public static void main(String[] args) throws IOException {  
        Solution s = new Solution();
		s.init();
    }
}

简版…😂

import java.util.*;
import java.math.*;
import java.io.*;
public class Main{
	static class Solution {
		int A = 5, B = 9, res;
		void dfs(int a, int b, int c) {
		    if (a > A || b > B)
		        return;
		    if (c < 0)
		        return;
			if (a == A && b == B) {
				if (c == 1)
				    res++;
				return;
			}
			dfs(a+1, b, 2*c);
			dfs(a, b+1, c-1);
		}
		void init() {
			Scanner sc = new Scanner(new BufferedInputStream(System.in));
			BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out));
			dfs(0, 0, 2);
			System.out.println(res);
		}
	}
    public static void main(String[] args) throws IOException {  
        Solution s = new Solution();
		s.init();
    }
}

复杂度分析

  • 时间复杂度:O(...)O(...)
  • 空间复杂度:O(...)O(...)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章