O(n) time O(1) space, concise Java solution


  • 0
    public class Solution {
        public int numWays(int n, int k) {
            if (n == 0) return 0;
            int same = 0, dif = k, total = k;
            for (int i = 1; i < n; i++) {
                same = dif;
                dif = (k - 1) * total;
                total = same + dif;
            }
            return total;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.