【回溯】C058_NK_牛牛的三角形(選數 / 二分)

一、Problem

牛牛有一個數組長度大小爲 n,數組中有 n 個正整數。現在牛牛請你從其中選出三個元素(注意選擇元素的下標不能相同,但是其值可以相同)組成一個三角形。

無法做到,請輸出一行一個字符串 “No solution”,反之請輸出這三個元素的值。

如果有多種組成三角形的元素組合,你可以輸出任意一種

輸入描述:

第一行是一個正整數 n,(3n102)n,(3\leq n \leq 10^2) 表示數組的元素個數。

接下來一行輸入n個正整數 aia_i 表示每個數組元素的值。

輸出描述:

如無法做到,請輸出一行一個字符串 “No solution”,反之請輸出這三個元素的值。

如果有多種組成三角形的元素組合,你可以輸出任意一種。

5
2 2 3 2 2

2 2 3

二、Solution

方法一:dfs

選夠了就檢查是否可以組成三角形…

import java.util.*;
import java.math.*;
import java.io.*;
public class Main {
	static class Solution {
        int n, a[];
        boolean done;
        List<Integer> all = new ArrayList<>(3), res;
        
        boolean check() {
            int a = all.get(0), b = all.get(1), c = all.get(2);
            if (a+b <= c || a + c <= b || b + c <= a) return false;
            if (a-b >= c || a - c >= b || b - c >= a) return false;
            return true;
        }
        void dfs(int idx) {
            if (done)  return;
            if (all.size() == 3) {
                if (check()) {
                    done = true;
                    res = new ArrayList(all);                    
                }
                return;
            }
            for (int i = idx; i < n; i++) {
                all.add(a[i]);
                dfs(i+1);
                all.remove(all.size()-1);
            }
        }
		void init() {
			Scanner sc = new Scanner(new BufferedInputStream(System.in));
            n = sc.nextInt();
            a = new int[n];
            for (int i = 0; i < n; i++) 
            	a[i] = sc.nextInt();
            dfs(0);
            if (res == null) System.out.println("No solution");
            else for (int i = 0; i < res.size(); i++)
                System.out.print(res.get(i) + " ");
        }
	}
    public static void main(String[] args) throws IOException {  
        Solution s = new Solution();
		s.init();
    }
}

複雜度分析

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