刷题感悟

题意:Given an array of integers, how many three numbers can be found in the array, so that we can build an triangle whose three edges length is the three numbers that we find?

根据题意 很明显是一个排列组合中的大小为n的集合不放回的取出m 有多少种做法? Cnm种

关键在于如何实现,如何保证多层循环时不重复取值。(起始位置在前一层后即可 。注意别在第一层后这样后面的会有所重复)

三层for循环 每一层都应该在上一层后面取值才不会有重复;

    /**
     * @param S: A list of integers
     * @return: An integer
     */
    public int triangleCount(int S[]) {
        // write your code here
        int sum =0;
        if(S.length<3)return sum;
        for(int i=0;i<S.length;i++){
            for(int j=i+1;j<S.length;j++){
                for(int k=j+1;k<S.length;k++)
                {
                    if(isTriangle(S[i],S[j],S[k]))sum++;
                }
            }
        }
        return sum;
    }
    Boolean isTriangle(int a,int b,int c){
        if(a+b>c&&a+c>b&&b+c>a)return true;
        return false;
    }
原文地址:https://www.cnblogs.com/zslzz/p/7235888.html