The Fake Geek's blog: Find possible triangle triplets
"Given a array of positive integers, find all possible triangle triplets that can be formed from this array.
eg: 9 8 10 7
ans: 9 8 10, 9 8 7, 9 10 7, 7 8 10
Note : array not sorted, there is no limit on the array length"
http://www.careercup.com/question?id=5863307617501184
I used backtracking for this problem. However, it may not be the best solution since the complexity is O(n!).
?????
Read full article from The Fake Geek's blog: Find possible triangle triplets
"Given a array of positive integers, find all possible triangle triplets that can be formed from this array.
eg: 9 8 10 7
ans: 9 8 10, 9 8 7, 9 10 7, 7 8 10
Note : array not sorted, there is no limit on the array length"
http://www.careercup.com/question?id=5863307617501184
public void triangleTriplet(int a[])
{
int n=a.length;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
for(int k=0;j<n;j++)
{
if(i!=j && j!=k && i!=k)
if(a[i]+a[j]>a[k] && a[j]+a[k]>a[i] && a[i]+a[k]>a[j])
{
System.out.println(a[i]+" "+a[j]+" "+a[k]);
}
}
}
}
}
I used backtracking for this problem. However, it may not be the best solution since the complexity is O(n!).
?????
public ArrayList<ArrayList <Integer>> possibleTriangle(int[] nums) { ArrayList<ArrayList <Integer>> rst = new ArrayList<>(); if (nums == null || nums.length == 0) return rst; ArrayList<integer> triplets = new ArrayList<integer>(); Arrays.sort(nums); getTriangle(rst, triplets, nums, 0); return rst; } private void getTriangle(ArrayList<ArrayList <Integer>> rst, ArrayList<integer> triplets, int[] nums, int start) { if (triplets.size() == 3 && triplets.get(0) + triplets.get(1) > triplets.get(2)) rst.add(new ArrayList<integer> (triplets)); for (int i = start; i < nums.length; i++) { if (i != start && nums[i] == nums[i - 1]) continue; triplets.add(nums[i]); getTriangle(rst, triplets, nums, i + 1); triplets.remove(triplets.size() - 1); } } public void printList(ArrayList<arraylist nteger="">> rst) { for (int i = 0; i < rst.size(); i++) System.out.println(rst.get(i)); }}