Valid Triangle Number (第十六周 数组)

来源:互联网 发布:python写入excel 编辑:程序博客网 时间:2024/06/06 13:11

Valid Triangle Number (第十六周 数组)

Given an array consists of non-negative integers, your task is to count the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.

For example,

Input: [2,2,3,4]
Output: 3
Explanation:
Valid combinations are:
2,3,4 (using the first 2)
2,3,4 (using the second 2)
2,2,3

算法思路

(1)其实这是一道签到题,快考试了,刷刷水题练练手感。
(2)给定一串数字,问能组成的三角形有多少组。
(3)那首先我们要知道给定三条边,如果验证这三条边能不能构成一个三角形。三角形的判断方法是任何两边之和大于第三边,两边之差小于第三边。那么我们就对于这3条边,任意的两两组合的边之和大于第三条边。
(4)然后我们就三重遍历这个数字数组,每重循环取出一条边,然后根据上面的方法判断能不能构成三角形。如果能,结果加一。

算法代码

class Solution {public:    int triangleNumber(vector<int>& nums) {        int res = 0;        int len = nums.size();        for(int i = 0 ; i < len; i++)            for(int j = i + 1; j < len; j++)                for(int k = j + 1 ; k < len; k++)                    if(istriangle(nums[i],nums[j],nums[k]))                        res++;        return res;    }    bool istriangle(int a, int b, int c){        if(a + b > c && b + c > a && a + c > b)            return true;        else            return false;    }};
原创粉丝点击