LeetCode062 Unique Paths

本文提供了LeetCode上第62题“Unique Paths”的多种解决方案,包括Java、C和Python三种语言实现,每种语言都展示了两种不同的算法思路,一种使用二维数组优化空间复杂度,另一种使用一维数组进一步优化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

详细见:leetcode.com/problems/unique-paths


Java Solution: github

package leetcode;

import java.util.Arrays;

public class P062_UniquePaths {
	public static void main(String[] args) {
		System.out.println(new Solution().uniquePaths(3, 3));
	}
	/*
	 * 	先写一份空间O(m * n),时间O(m * n)的版本
	 * 	1 ms
	 * 	5.22%
	 */
	static class Solution {
	    public int uniquePaths(int m, int n) {
	    	if (m < 1 || n < 1)
	    		return 0;
	        int[][] route = new int[m][n];
	        Arrays.fill(route[0], 1);
	        for (int i = 1; i < m; i ++)
	        	route[i][0] = 1;
	        for (int i = 1; i < m; i ++) {
	        	for (int j = 1; j < n; j ++) {
	        		route[i][j] = route[i - 1][j] + route[i][ j - 1];
	        	}
	        }
	        return route[m - 1][n - 1];
	    }
	}
	/*
	 * 	1 ms
	 *  5.22% 
	 */
	static class Solution2 {
	    public int uniquePaths(int m, int n) {
	    	if (m < 1 || n < 1)
	    		return 0;
	    	if (m > n)
	    		return uniquePaths(n, m);
	        int[] route = new int[m];
	        Arrays.fill(route, 1);
	        for (int i = 1; i < n; i ++)
	        	for (int j = 1; j < m; j ++)
	        		route[j] += route[j - 1];
	        return route[m - 1];
	    }
	}
}


C Solution: github

/*
    url: leetcode.com/problems/unique-paths
    AC 3ms 2.33%
*/

int uniquePaths(int m, int n) {
    int* dp = (int*) malloc(sizeof(int) * n);
    int i = 0, j = 0;
    for (i = n-1; i > -1; i --) {
        dp[i] = 1;
    }
    for (j = m-2; j > -1; j --) {
        for (i = n-2; i > -1; i --) {
            dp[i] += dp[i+1];
        }
    }
    i = dp[0];
    free(dp);
    return i;
}

int main() {

}


Python Solution: github

#coding=utf-8

'''
    url: leetcode.com/problems/unique-paths
    @author:     zxwtry
    @email:      zxwtry@qq.com
    @date:       2017年4月13日
    @details:    Solution: 79ms 10.36%
'''

class Solution(object):
    def uniquePaths(self, m, n):
        """
        :type m: int
        :type n: int
        :rtype: int
        """
        dp = [1] * n
        for j in range(m-2, -1, -1):
            for i in range(n-2, -1, -1):
                dp[i] += dp[i+1]
        return dp[0]


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值