1 public class test 2 { 3 public static void main(String[] args) 4 { 5 Scanner input = new Scanner(System.in); 6 int m = input.nextInt(); 7 int n = input.nextInt(); 8 //iterative 9 System.out.println(uniquePath(m, n)); 10 //recursive 11 int[][] dp = new int[m][n]; 12 System.out.println(uniquePath(m - 1, n - 1, dp)); 13 } 14 15 //iterative 16 public static int uniquePath(int m, int n) //时间复杂度: O(n^m) 17 { 18 int[][] dp = new int[m][n]; 19 20 //第一行均赋为1 21 for(int j = 0; j < dp[0].length; j++) 22 dp[0][j] = 1; 23 24 //第一列均赋为1 25 for(int i = 0; i < dp.length; i++) 26 dp[i][0] = 1; 27 28 for(int i = 1; i < dp.length; i++) 29 for(int j = 1; j < dp[0].length; j++) 30 dp[i][j] = dp[i][j - 1] + dp[i - 1][j]; 31 32 //返回右下角的值 33 return dp[dp.length - 1][dp[0].length - 1]; 34 } 35 36 //recursive 37 public static int uniquePath(int m, int n, int[][] dp) 38 { 39 //递归终止条件 40 if(m == 0 || n == 0) 41 return 1; 42 43 //避免重复计算 44 if(dp[m - 1][n] == 0) 45 dp[m - 1][n] = uniquePath(m - 1, n, dp); 46 if(dp[m][n - 1] == 0) 47 dp[m][n - 1] = uniquePath(m, n - 1, dp); 48 dp[m][n] = dp[m - 1][n] + dp[m][n - 1]; 49 return dp[m][n]; 50 } 51 }
(HW)uniquePath(Java)
猜你喜欢
转载自www.cnblogs.com/Huayra/p/10939694.html
今日推荐
周排行