Guest User

Untitled

a guest
Mar 19th, 2018
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. /*
  5. Given an array consists of non-negative integers, your task is to count the number of triplets chosen
  6. from the array that can make triangles if we take them as side lengths of a triangle.
  7. Example 1:
  8. Input: [2,2,3,4]
  9. Output: 3
  10. Explanation:
  11. Valid combinations are:
  12. 2,3,4 (using the first 2)
  13. 2,3,4 (using the second 2)
  14. 2,2,3
  15.  
  16.  
  17. [2,2,3,4]
  18. i j k
  19.  
  20. set = {(2,3,4),}
  21. i = 0
  22. j = 2
  23. k = 3
  24.  
  25. Note:
  26. The length of the given array won't exceed 1000.
  27. The integers in the given array are in the range of [0, 1000].
  28.  
  29. */
  30.  
  31. class Solution {
  32.  
  33. public static void main(String[] args) {
  34. // int[] arr = new int[]{2, 2, 3, 4}; // 1, 1, 1, 2,
  35. // System.out.println(String.format("Expected=%d, found=%d", 3, findCombinations(arr)));
  36.  
  37. int[] arr = new int[]{1, 1, 1, 2}; // 1, 1, 1, 2, 3, 4
  38. // 1, 2, 2, 3, 4 2, - Julia explained the two pointer technique alternative design.
  39. // left right
  40. //
  41. System.out.println(String.format("Expected=%d, found=%d", 1, findCombinations(arr)));
  42. }
  43.  
  44. private static Integer findCombinations(int[] arr) {
  45.  
  46. if (arr == null || arr.length == 0) return 0;
  47.  
  48. int num = 0;
  49. Arrays.sort(arr);
  50. for (int i = 0; i < arr.length - 2; i++) {
  51. int j = i + 1;
  52. int k = arr.length - 1;
  53. num += findCombinations(arr, i, j, k);
  54. }
  55.  
  56. return num;
  57. }
  58.  
  59. private static int findCombinations(int[] arr, int i, int j, int k) {
  60. if (j >= k) return 0;
  61. int num = 0;
  62. if (arr[i] + arr[j] > arr[k]) {
  63. System.out.println(String.format("Found combination i=%d, j=%d, k=%d", i, j, k));
  64. num++; // design has defect -> not efficient -> n^2 increment -> add range of number/
  65. } else {
  66.  
  67. }
  68.  
  69. num += findCombinations(arr, i, j + 1, k);
  70. num += findCombinations(arr, i, j, k - 1);
  71. return num;
  72. }
  73. }
Add Comment
Please, Sign In to add comment