Snapchat - ColorSum
给一些RGB的点,比如(86, 5, 211), (128, 99, 5), 再一个target点,看使用这些给的点能不能叠加得到target,每个点只能用一次
就是最基本的backtracking
1 public class ColorSum { 2 static class Color { 3 int r; 4 int g; 5 int b; 6 public Color(int r, int g, int b) { 7 this.r = r; 8 this.g = g; 9 this.b = b; 10 } 11 12 public void add(Color color) { 13 this.r = (this.r + color.r > 255)? 255: (this.r + color.r); 14 this.g = (this.g + color.g > 255)? 255: (this.g + color.g); 15 this.b = (this.b + color.b > 255)? 255: (this.b + color.b); 16 } 17 18 public boolean substract(Color color) { 19 if(color.r > this.r || color.g > this.g || color.b > this.b) { 20 return false; 21 } 22 this.r = this.r - color.r; 23 this.g = this.g - color.g; 24 this.b = this.b - color.b; 25 return true; 26 } 27 28 public boolean equalsZero() { 29 return r == 0 && g == 0 && b == 0; 30 } 31 32 public String toString() { 33 return "(" + r + ", " + g + ", " + b + ")"; 34 } 35 } 36 37 public boolean canSum(List<Color> colors, Color target) { 38 if(colors == null || colors.size() == 0 || target == null) { 39 return false; 40 } 41 return helper(colors, 0, target); 42 } 43 44 private boolean helper(List<Color> colors, int index, Color target) { 45 if(target.equalsZero()) { 46 return true; 47 } 48 for(int i = index; i < colors.size(); i++) { 49 if(target.substract(colors.get(i))) { 50 if(helper(colors, i + 1, target)) { 51 return true; 52 } 53 target.add(colors.get(i)); 54 } 55 } 56 return false; 57 } 58 59 public static void main(String[] args) { 60 ColorSum sample = new ColorSum(); 61 List<Color> colors = new ArrayList<>(); 62 colors.add(new Color(86, 5, 211)); 63 colors.add(new Color(128, 99, 5)); 64 colors.add(new Color(92, 25, 6)); 65 colors.add(new Color(16, 45, 4)); 66 Color target = new Color(236, 169, 15); 67 System.out.println(sample.canSum(colors, target)); 68 } 69 }

浙公网安备 33010602011771号