1 棋盤問題 從棋盤左下角,走到右上方,每一步只有向上和向右兩種選擇
| 1 |
1 |
1 |
1 |
1 |
| 1 |
2 |
3 |
4 |
5 |
| 1 |
3 |
6 |
10 |
15 |
| 1 |
4 |
10 |
20 |
35 |
public static int choose(int m,int n){int[][] a = new int[m][n];for(int i=0;i<m;i++) a[i][0] = 1;for(int j=0;j<n;j++) a[0][j] = 1;for(int i=1;i<m;i++)for(int j=1;j<n;j++)a[i][j] = a[i-1][j] + a[i][j-1];return a[m-1][n-1];}
2
public class FindDouble2 { /** * @param args * 搜狗:有N個正實數(注意是實數,大小升序排列) x1 , x2 ... xN,另有一個實數M。 需要選出若干個x,使這幾個x的和與 M 最接近。 請描述實現演算法,並指出演算法複雜度。 * 思路:對於每一個數字,都分兩種情況,取它或者不取,有點類似於0/1背包問題,但是之前只會那種加起來正好等於某個值的這種選擇問題。 */private double all[];//記錄所有的實數數組private boolean result[];//記錄最終結果private Double min;//用於記下最優結果時候的值 public FindDouble2(double all[]){this.all=all;}/** * * @param i 當前處理的實數下標 * @param m 當前剩餘值,為(m-all[i]) * @param etemp 當前的結果序列 * @param exist 當前個取false or true */public void process(int i,double m,boolean etemp[],boolean exist){if(min==null) min = m;if(result==null) result = new boolean[all.length];if(exist){m=m-all[i];}etemp[i] = exist;if(Math.abs(m)<min){min = Math.abs(m);System.arraycopy(etemp, 0, result, 0, etemp.length);}if(i<all.length-1){process(i+1,m,etemp,true);process(i+1,m,etemp,false);}} public static void main(String[] args) {//double[] A = new double[] {1.5,2.5,3.0};double[] A = new double[]{1,2,4,6,9,10};boolean[] E = new boolean[A.length];FindDouble2 fd = new FindDouble2(A);//fd.process(0,5.5,E,true);//fd.process(0,5.5,E,false); fd.process(0, 11, E, true);fd.process(0, 11, E, false);for (int i = 0; i < fd.result.length; i++) {System.out.print(fd.result[i]);}}}