【回溯】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(...)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章